BatteryManager--获取电量

public class BatteryActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_battery;
    private BatteryBoastcaseReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_battery);

        //找到需要的控件
        initView();

        //设置监听
        initListener();

    }

    private void initView() {

        btn_battery = (Button) findViewById(R.id.btn_battery);


    }

    private void initListener() {

        btn_battery.setOnClickListener(this);

    }


    /** * 点击发送广播 */
    @Override
    public void onClick(View v) {

        receiver = new BatteryBoastcaseReceiver();

        //创建意图过滤器
        IntentFilter intentFilter = new IntentFilter();

        //Intent.ACTION_BATTERY_CHANGED 电量发生改变
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);

        registerReceiver(receiver, intentFilter);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //反注册广播
        unregisterReceiver(receiver);

    }
}
public class BatteryBoastcaseReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {

        //判断如果是电池的电量发生改变
        if (Intent.ACTION_BATTERY_CHANGED == intent.getAction()) {

            //电池的电量等级
            int level = intent.getIntExtra("level", -1);
            //电池的总电量
            int scale = intent.getIntExtra("scale", -1);


            Log.e("tag", "level" + level + ":scale" + scale);

            //电量百分比
            int process = level * 100 / scale;

            //创建一个Dialog
            AlertDialog.Builder dialog = new AlertDialog.Builder(context);

            dialog.setTitle("电池电量").setMessage("电池电量为:" + process + "%");
            //取消按钮
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            //将对话框展示出来
            dialog.show();
        }

    }
}

你可能感兴趣的:(电池电量)