Is it possible to determine whether an Android device is connected to a computer or just power?

I was wondering if it is possible to specifically determine whether the Android device is connected to a computer or simply to power.

The main reason is that I would like my phone to have “Stay Awake” when it was connected to the computer during development, but not when it was plugged in at night.

I thought that if I could tell what I was connected to, I could use ACTION_POWER_CONNECTED to start the service and check which USB is connected.

+3
source share
3 answers

In fact, I found the exact way to choose whether to turn on the screen when connected to AC, USB, or either by searching for the source in http://google.com/codesearch#409TP6F96yI/src/com/android/settings/DevelopmentSettings.java&l=95

Permission Required: android.permission.WRITE_SETTINGS

 Settings.System.putInt(getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, mKeepScreenOn.isChecked() ? (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB) : 0); 

For AC: BatteryManager.BATTERY_PLUGGED_AC

For USB: BatteryManager.BATTERY_PLUGGED_USB

For Either: (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB)

+1
source

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(); } } }; // register the receiver to listen to battery change IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(receiver, filter); 

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

+4
source

Well, if it is connected to a power source, and you want it to just fall asleep, press the POWER button.

-3
source

Source: https://habr.com/ru/post/1482625/


All Articles