Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

android - Get battery level before broadcast receiver responds for Intent.ACTION_BATTERY_CHANGED

I have a broadcast receiver in my program to get react to the battery level like so:

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int level = intent.getIntExtra("level", 0);
        // do something...
    }
}

    registerReceiver(this.mBatInfoReceiver, 
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

However this code has to wait for the battery status to be updated so if you have a GUI element that needs to be set based on the battery level it must wait for a battery event to occur. Is there a way to nudge this to get it working or simply run some code to see what the battery level was on the last broadcast?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how to get the battery level without registering a receiver:

Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
                    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
double scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
double level = -1;
if (rawlevel >= 0 && scale > 0) {
    level = rawlevel / scale;
}

It can use a null BroadcastReceiver because of the sticky nature of the broadcast.

It uses the getApplicationContext() trick in case you are in a intent receiver and get the exception:

android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...