android 广播监控手机电量

来源:互联网 发布:店铺淘宝客交流论坛 编辑:程序博客网 时间:2024/04/28 14:08

问题很简单 直接给出代码

<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;@Overrideprotected 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();// 注册receiverregisterReceiver(batteryReceiver, intentFilter);}/** * 广播接受者 */private class BatteryReceiver extends BroadcastReceiver {@Overridepublic 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();}}}}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(batteryReceiver);}}