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
391 views
in Technique[技术] by (71.8m points)

power management - Detect Changing Battery state at every percentage in android

i want to detect battery change at every percentage. I am able to detect battery level once with broadcast receiver. But its not updating value automatically when % change from 66 to 67.

Here is my code.

   private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                Log.i("Battery CHANGED******",":: IN RECEIVER");

                int rawlevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                btnConsumer.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);

    }

Added permission

 <uses-permission android:name="android.permission.BATTERY_STATS"></uses-permission>

It detect 66 but when it change 65 or 67 it will not update value. or not display log too

I want to make it like i can get every change.

Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First, you do not need the BATTERY_STATS permission.

Second, the very first line of your onReceive() unregisters your BroadcastReceiver, thereby preventing you from getting any further updates.

Third, there is no guarantee that you will have battery information delivered to you for each and every 1% change. Many Motorola phones, for example, only send ACTION_BATTERY_CHANGED every 10% until the battery gets low. The decision on how frequently to broadcast ACTION_BATTERY_CHANGED is up to the device manufacturer, not you.


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

...