-1

I'd like to start a program in Android 10 right after boot in a generic way. Can anyone shed light on this?

I tried writing a app for Android Studio that handles BOOT_COMPLETED event that calls the app, and the app is supposed to print hello World after boot. But it did not do anything in Pixel a.

1 Answers1

0

Android 9 and below

Register BroadcastReceiver in manifest

<receiver android:name=".StartOnBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
    </intent-filter>
</receiver>

StartOnBootReceiver code:

class StartOnBootReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {
        if (intent?.action == Intent.ACTION_BOOT_COMPLETED) {
            val activityIntent = Intent(context, MainActivity::class.java)
            activityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(activityIntent)
        }
    }
}

On system startup, your BroadcastReceiver will be launched, then it will launch MainActivity.

Android 10 and above

Starting from Android 10, the startActivity method only works when it is called by an application that is in the foreground. Therefore, you may need to request the following permissions:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACTION_MANAGE_OVERLAY_PERMISSION" />

Now request the REQUEST_OVERLAY_PERMISSION if android version is above 10:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Settings.canDrawOverlays(this)) {
      val intent = Intent(
          Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
          Uri.parse("package:$packageName")
      )
      startActivityForResult(intent, REQUEST_OVERLAY_PERMISSION)
}

Once the permission is granted you can again use the startActivity method from your BroadcastReceiver.

alSan
  • 11
  • 2