Android 获取手机电量信息

1、添加接收系统电量广播的类

    /*
     * 接收手机电量广播
     */
    class BatteryReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                // current level
                int level = intent.getIntExtra("level", 0);
                // all scale
                int scale = intent.getIntExtra("scale", 100);
                battery.setText((level*100)/scale + "%");
            }
        }
    }

2、注册电量广播

//电量广播注册
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(new BatteryReceiver(), filter);

你可能感兴趣的:(Android,基础)