Skip to content

Instantly share code, notes, and snippets.

@9re
Created June 5, 2012 01:46
Show Gist options
  • Save 9re/2871934 to your computer and use it in GitHub Desktop.
Save 9re/2871934 to your computer and use it in GitHub Desktop.
Log battery level periodically
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