简体   繁体   中英

Auto start an app when charger is plugged

I will make a new Android application. How to to auto-start it as soon as the mobile is plugged into charging?

If this is successfully done, then the application will be opened automatically when the charger is plugged to the mobile phone.

You need a broadcast receiver for this.

Add this to your manifest:

 <receiver android:name=".PowerConnectionReceiver">
  <intent-filter>
  <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
  <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
  </intent-filter>
 </receiver>

Now add this to your class

public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) { 
    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || 
                                status == BatteryManager.BATTERY_STATUS_FULL;



    int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharging = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharging = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

    if (isCharging) {

       Intent i = new Intent();
       i.setClassName("com.className", "com.classname.YourActivityClass");
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(i)
    }

 }
}

Don't forget to replace things like com.className with yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM