androidandroid-activityandroid-8.1-oreo

Is there a workaround for launching an activity at ACTION_POWER_CONNECTED on Oreo?


I'm currently developing an app for a client that is supposed to launch when it's charging. The only way that I know to do this is with the manifest like so:

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

But for Android Oreo, this is no longer a valid option and causes an error to print along the lines of "Background execution not allowed".

Has anyone found a good workaround for this problem? Essentially, I need a way to launch an activity when the power is connected and have it remain open until the power is disconnected. The phone won't be running any other services or activities that I could use to create an explicit broadcast.


Solution

  • But for Android Oreo, this is no longer a valid option and causes an error to print along the lines of "Background execution not allowed".

    From Oreo While an app is in the foreground, it can create and run both foreground and background services freely. So 1 possible approach can be to create a foreground service that monitors the status of charging/not charging using BatteryManager class - this class broadcasts all battery and charging details in a sticky Intent that includes the charging status.

    val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
    val batteryStatus = context.registerReceiver(null, ifilter)
    
     val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
     val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
    

    Now that you know whether your device is charging or not.

    Next from same Service class code - based on the status of charging- you can launch the YourActivity as below ,

    Intent i = new Intent();
    i.setClass(this, YourActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
    

    Now starting an activity like this may not be the best user experience - and hence you may want to consider using Notification system of android to update/inform the user about the status of charging