Creating an Android app that automatically starts after the device reboots can be essential for many applications, such as reminders, alarms, or persistent background services. This article will guide you through the process of implementing this functionality using Java, and integrating it seamlessly with your app.
Automatically Launch Your Android App on Device Boot – Flutter
Introduction
To achieve this, you need to:
- Create a
BroadcastReceiver
that listens for theBOOT_COMPLETED
action. - Update the
MainActivity
to handle necessary permissions. - Configure the
AndroidManifest.xml
to declare permissions and register the receiver. - Handle battery optimization to ensure consistent behavior.
Step-by-Step Guide
Step 1: Create the BroadcastReceiver
The BroadcastReceiver
listens for the BOOT_COMPLETED
action and starts the main activity of your app when the device boots up.
package com.example.boot;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class autostart extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Autostart", "Received BOOT_COMPLETED broadcast");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d("Autostart", "Starting MainActivity");
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
}
Step 2: Update MainActivity
In MainActivity
, request permission to draw overlays, which might be necessary for certain functionalities in modern Android versions.
package com.example.boot;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle; // Add this import statement
import android.provider.Settings;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(getApplicationContext())) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 7);
}
}
}
Step 3: Configure AndroidManifest.xml
Declare the necessary permissions and register the BroadcastReceiver
in your AndroidManifest.xml
.
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:label="boot"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<receiver
android:enabled="true"
android:exported="true"
android:name=".autostart"
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>
</application>
</manifest>
Step 4: Handle Battery Optimization
Modern Android versions come with aggressive battery optimization techniques that might prevent your app from receiving the BOOT_COMPLETED
broadcast. Ensure users disable battery optimization for your app to maintain consistent behavior.
Here’s how to prompt users to disable battery optimization:
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
public class BatteryOptimizationHelper {
public static void requestDisableBatteryOptimization(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName = context.getPackageName();
if (!Settings.canDrawOverlays(context)) {
intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + packageName));
context.startActivity(intent);
}
}
}
}
Conclusion
With these steps, your Android app will automatically launch when the device is restarted. It’s essential to handle user consent appropriately and consider the impact of battery optimization settings on your app’s behavior.
By following this guide, you can enhance the functionality of your Android application to provide a better user experience through persistent operations.