There have been many questions like this before, and I've tried to implement the answers but it doesn't work on Android 11. I want my flutter app will be started/opened automatically after booting was completed.
this is my receiver MainActivityReceiver.kt
package com.mypackage
import android.content.BroadcastReceiver
import android.content.Context;
import android.content.Intent;
class MainActivityReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
val i = Intent(context, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
}
}
and I added some code on AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<receiver
android:enabled="true"
android:exported="true"
android:name="com.myPackage.MainActivityReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
EDIT
I found https://stackoverflow.com/a/63250729/11445944, but how to implement it on flutter?.
How to add this code on flutter MainActivity.kt
if (!Settings.canDrawOverlays(getApplicationContext())) {
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
myIntent.setData(uri);
startActivityForResult(myIntent, REQUEST_OVERLAY_PERMISSIONS);
return;
}
I've added it on my MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!Settings.canDrawOverlays(getApplicationContext())) {
val myIntent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
val uri: Uri = Uri.fromParts("package", getPackageName(), null)
myIntent.setData(uri)
startActivityForResult(myIntent, REQUEST_OVERLAY_PERMISSIONS)
return
}
}
And I got the error on build
[ +2 ms] e: project_path/app/MainActivity.kt: (32, 5): 'onCreate' overrides nothing
[ +24 ms] e: project_path/app/src/main/kotlin/package/MainActivity.kt: (32, 47): Unresolved reference: Bundle
[ +7 ms] e: project_path/app/src/main/kotlin/package/MainActivity.kt: (34, 14): Unresolved reference: Settings
[ +3 ms] e: project_path/app/src/main/kotlin/package/MainActivity.kt: (35, 35): Unresolved reference: Settings
[ +3 ms] e: project_path/app/src/main/kotlin/MainActivity.kt: (38, 46): Unresolved reference:
REQUEST_OVERLAY_PERMISSIONS
SOLVED
The error was gone after I import 2 lines code
import android.os.Bundle
import android.provider.Settings
and don't forget to initialize var REQUEST_OVERLAY_PERMISSIONS = 100
. Now my app run automatically after booting was completed on Android 11.