I tried using the sample code in this tutorial but it seems outdated and it did not work. So what changes do I have to make and to what files to have my app start automatically when Android finishes booting up?
I tried using the sample code in this tutorial but it seems outdated and it did not work. So what changes do I have to make and to what files to have my app start automatically when Android finishes booting up?
For Android 10 there is background restrictions.
For android 10 and all version of android follow this steps to start an app after a restart or turn on mobile
Add this two permission in Android Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Add this in your application tag
<receiver
android:name=".BootReciever"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Add this class to start activity when boot up
public class BootReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, SplashActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}}
We need Draw overlay permission for android 10
so add this in your first activity
private fun requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.packageName)
)
startActivityForResult(intent, 232)
} else {
//Permission Granted-System will work
}
}
}
The Sean's solution didn't work for me initially (Android 4.2.2). I had to add a dummy activity to the same Android project and run the activity manually on the device at least once. Then the Sean's solution started to work and the BroadcastReceiver was notified after subsequent reboots.
For flutter user, you can create a file named MainActivityReceiver.kt in package folder. eg. android/app/src/main/kotlin/com/your_company/package.
MainActivityReceiver.kt:
package com.your_company.package
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)
}
}
}
Modify your AndroidManifest.xml file refer to the first answer.