赞
踩
问题很简单 直接给出代码
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/tv_cell"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="电池电量"
- android:textColor="#000000"
- android:layout_margin="10dp"
- android:textSize="18dp" />
- </LinearLayout>
-
- </RelativeLayout>
监听需要权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- package cn.itcast.BatteryChecker;
-
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo.State;
- import android.os.Bundle;
- import android.widget.TextView;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
-
- private TextView tv_cell;
- private BatteryReceiver batteryReceiver;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- tv_cell = (TextView) findViewById(R.id.tv_cell);
- // 注册广播接受者java代码
- IntentFilter intentFilter = new IntentFilter(
- Intent.ACTION_BATTERY_CHANGED);
- batteryReceiver = new BatteryReceiver();
- // 注册receiver
- registerReceiver(batteryReceiver, intentFilter);
- }
-
- /**
- * 广播接受者
- */
- private class BatteryReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
- int level = intent.getIntExtra("level", 0);
- tv_cell.setText("电池电量为" + level + "%");
-
- if (level < 15) {
- Toast.makeText(MainActivity.this, "电池电量不足15%,请及时充电", 0)
- .show();
- }
- }
- }
-
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- unregisterReceiver(batteryReceiver);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。