Android常亮设置以及读取电量

1.adnroid常亮设置

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

2.读电量的方式(广播方式实现)

[1]新建一个广播类去接收系统电池变化信息,在这里通过调用intent.getExtras()方法得到intent携带的Bundle集合
其中有当前电量字段”level”,总电量”scale”

package com.twei.battery;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.TextView;

/**
 * 监听获取手机系统剩余电量
 * Created by Twei on 2017/3/14.
 */
public class BatteryReceiver extends BroadcastReceiver {
    private TextView pow;

    public BatteryReceiver(TextView pow) {
        this.pow = pow;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int current = intent.getExtras().getInt("level");// 获得当前电量
        int total = intent.getExtras().getInt("scale");// 获得总电量
        int percent = current * 100 / total;
        pow.setText(percent + "%");
    }
}

[2]在需要使用的activity动态注册广播监听电池电量变化

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
receiver = new BatteryReceiver(tvElectric);
registerReceiver(receiver, filter);

[3]在销毁方法中注销监听广播

unregisterReceiver(receiver);

你可能感兴趣的:(Android)