/** *检测手机电量变化 * 使用registerReceiver(receiver, intentFilter);来注册广播,而不是在清单文件中注册<receiver><receiver> * 需要添加权限: * <uses-permission android:name="android.permission.BATTERY_STATS"/> * 在onResume()中注册广播 * registerReceiver(receiver, intentFilter); * 在onPause()中注销广播 * unregisterReceiver(receiver); *广播接收者中检测处理电量的变化 * 检测意图 电量变化:Intent.ACTION_BATTERY_CHANGED * * 获取当前电量 * int level = intent.getIntExtra("level", 0); * 获取总电量 * int scale = intent.getIntExtra("scale", 100); * * */ public class MainActivity extends Activity { TextView tv; private BroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView)findViewById(R.id.tv); } @Override protected void onResume() { super.onResume(); receiver = new MyReceiver(); //意图过滤器, 过滤电量变化 IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); //注册广播接收者 registerReceiver(receiver, intentFilter); } @Override protected void onPause() { super.onPause(); //注销广播接收者 unregisterReceiver(receiver); } /** * 广播接收者 */ private class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {//系统的电量变化action //当前电量 "level" int level = intent.getIntExtra("level", 0); //总电量 int scale = intent.getIntExtra("scale", 100); //显示 tv.setText("当前电量"+ (level * 100) / scale + "%"); } } } }
时间: 2024-11-05 16:38:09