简体   繁体   中英

Proper optimized way to monitor battery level in android

I want to monitor the battery level and if it reaches certain level, i want to DO-SOMETHING. What I am worried about is draining too much battery unnecessarily.

Using a service will keep on running in the background. Also if i used android.intent.action.BATTERY_CHANGED intent, it will check for every single change in the battery level. This two methods might drain unnecessary battery according to my requirements.

So, if I use AlarmManager(which is also a service handled by OS), it will check that battery level every user-defined(appropriate time).

The following are codes which I have implemented.

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

private AlarmManager mAlarmManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        mAlarmManager= (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent intentAlarm = new Intent(this, AlarmReceiverTest.class);

        // User defined time
        long fiveMin= (AlarmManager.INTERVAL_FIFTEEN_MINUTES/3); // adjustment here

        mAlarmManager.setRepeating(AlarmManager.RTC,
                    System.currentTimeMillis()+fiveMin, oneMin, 
                    PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));

    }

}

Broadcast receiver:

public class AlarmReceiverTest extends BroadcastReceiver {

@Override
public void onReceive(Context pContext, Intent arg1) {

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = pContext.registerReceiver(null, ifilter);

    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
    int percent = (level*100)/scale;

    if(percent== myThreshold)
        //DO-SOMETHING
}

}

In manifest:

<receiver android:name="AlarmReceiverTest">
    <intent-filter>
        <action android:name="android.intent.action.BATTERY_CHANGED"/>
    </intent-filter>
</receiver>

Permission:

android.permission.BATTERY_STATS

Since its a repeating alarm, it will keep on checking even if the application is closed.

eg.: DO-SOMETHING: might be lock the application if the application was already opened OR not allowed to open the application if it was already closed.

Is this the proper way to do and is my understanding correct? Kindly suggest me if there is any other proper way to do.

EDITED:

If I were to check the battery level for every 5-10 hours of interval, what would be the best way to do so?

You don't need to use AlarmManager class . Your application consumes more battery if you use AlarmManager class.

The easiest way to do it is using a broadcast listener for the intent ACTION_BATTERY_CHANGED.

public class AlarmReceiverTest extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int batteryLevel = intent.getIntExtra(
                    BatteryManager.EXTRA_LEVEL, 0);
            int maxLevel = intent
                    .getIntExtra(BatteryManager.EXTRA_SCALE, 0);
            int batteryHealth = intent.getIntExtra(
                    BatteryManager.EXTRA_HEALTH,
                    BatteryManager.BATTERY_HEALTH_UNKNOWN);
            float batteryPercentage = ((float) batteryLevel / (float) maxLevel) * 100;

            // Do something with batteryPercentage and batteryHealth.
            // batteryPercentage here ranges 0-100
        }
    }

onReceive runs every time the battery level changes.

In your main activity register the broadcast receiver:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AlarmReceiverTest mBatteryLevelReceiver = new AlarmReceiverTest();
    registerReceiver(mBatteryLevelReceiver, new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM