Android Broadcast Receiver battery life every 10 mins or change, can it go in its own thread?
I would like to write an application (for research) that makes a timestamp every time the battery level changes. If I can't do that, I want to make it so it takes a battery reading every 10 or so minutes.
I have this BroadcastReceiver
code but I am not sure where to put it.
My application keeps crashing with the following exception:
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.mdog.datareceive.Receive$1@43c9cd10
In the onCreate
of my activity I spawn 3 AsyncTask threads that do stuff in the background. Where would be a good place to put the broadcast receiver?
I have tried in the onCreate
and I have tried in a new method that gets called by one of the background tasks. I think the problem might be that the function the BroadcastRecevier
code is in might be ending prematurely?
Is there anyway I could put it in its own thread so that it just waits for broadcasts?
Code:
batteryLevelTimeStamps = new LinkedList<String>();
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
batteryLevel = level + "%";
batteryLevelTimeStamps.add("At time: " + new Date().toString() + " the battery level is:" +batteryLevel);
out.print("At time: " + new Date().toString() + " the battery level is:" +batteryLevel + " in onCreate\n");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY开发者_JAVA百科_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
I think you want to look at using the AlarmManager. You can set an alarm when the phone boots up, and after you receive that alarm, you can check the battery and set another alarm 10 minutes in the future.
Using AlarmManager is better than your own thread because
- It allows the phone to go to low power usage mode during the ten minute wait
- At the end of 10 minutes, it will wake up the phone if it is currently in that low power state.
精彩评论