First you need to register the receiver to listen to Intent.ACTION_BATTERY_CHANGED and check BatteryManager.BATTERY_PLUGGED_USB . Below is the code for this:
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(); } } };
You also need permission in your AndroidManifest.xml to enable wakeup.
<uses-permission android:name="android.permission.WAKE_LOCK" />
Another note: at some point you will need to unregister the recipient. You can specify that through the settings page you can call unregisterReceiver
source share