Created
June 5, 2012 01:46
-
-
Save 9re/2871934 to your computer and use it in GitHub Desktop.
Log battery level periodically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.battery; | |
import android.app.AlarmManager; | |
import android.app.PendingIntent; | |
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.util.Log; | |
public class BatteryLevelReceiver extends BroadcastReceiver { | |
private static final long DURATION = 1000 * 60 * 60; // every 1 hour | |
private static final String TAG = "[battery]"; | |
private static final String BATTERY_TEST = "com.example.battery.BATTERY_TEST"; | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
String action = intent.getAction(); | |
context = context.getApplicationContext(); | |
if (BATTERY_TEST.equals(action)) { | |
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); | |
context.registerReceiver(this, filter); | |
context.registerReceiver(null, filter); | |
PendingIntent operation = PendingIntent.getBroadcast( | |
context, | |
0, | |
new Intent(action), | |
PendingIntent.FLAG_UPDATE_CURRENT); | |
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); | |
alarmManager.set( | |
AlarmManager.RTC_WAKEUP, | |
System.currentTimeMillis() + 3000, | |
operation); | |
} else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { | |
context.unregisterReceiver(this); | |
int level = intent.getIntExtra("level", 0); | |
Log.d(TAG, "level: " + level); | |
// TODO: log battery level to file | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment