First you need to register a receiver to listen to Intent.ACTION_BATTERY_CHANGED
and check for the BatteryManager.BATTERY_PLUGGED_USB
. Below is the code to do so:
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Connected to USB, Stay Awake", Toast.LENGTH_LONG).show();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeLock");
wl.acquire();
}
}
};
// register the receiver to listen to battery change
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
You also need the permission in your AndroidManifest.xml to enable staying awake
<uses-permission android:name="android.permission.WAKE_LOCK" />
One other note, at some point you will need to unregister the receiver. You could provide that via settings page to call unregisterReceiver