Automatically Launch Your Android App on Device Boot – Flutter

Making an Android app that launches automatically upon device reboots can be very helpful for many apps, including background persistent services, alarms, and reminders. We’ll walk you through the process of implementing this feature in Java and integrating it with a Flutter activity in this article.

Automatically Launch Your Android App on Device Boot Using Java

Overview
In order to do this, we’ll:

Introduction

To achieve this, we will:

  1. Create a BroadcastReceiver to listen for the BOOT_COMPLETED action.
  2. Update the MainActivity to handle necessary permissions.
  3. Configure the AndroidManifest.xml to declare permissions and register the receiver.
  4. Handle battery optimization to ensure consistent behavior.

Step-by-Step Implementation

Create the BroadcastReceiver

A BroadcastReceiver that watches for the BOOT_COMPLETED action must first be created. When the device boots up, this receiver will start your app’s primary activity.

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);
        }
    }
}

Update MainActivity

We will ask for permission to draw overlays in MainActivity, as some features in more recent Android versions may require it.

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);
        }
    }
}

Configure AndroidManifest.xml

Make sure the BroadcastReceiver is registered in your AndroidManifest.xml file and that the required permissions are declared.

<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>

Handle Battery Optimization

Aggressive battery optimisation strategies in modern Android versions may prevent your app from getting the BOOT_COMPLETED broadcast. To maintain consistent behaviour, make sure users disable battery optimisation for your programme.To ask users to turn off battery optimisation, follow these steps:

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);
            }
        }
    }
}

In summary
You can configure your Android app to run automatically on device restarts by following these steps. Don’t forget to manage user consent properly and take into account how your app will behave depending on the battery optimisation options.

Through persistent operations, you may improve the functionality of your Android application and offer a better user experience by following this guidance.

Hey folks, I'm Vivek Kumar Pandey, a software engineer with a passion for crafting elegant solutions to complex problems. From the bustling streets of Mumbai to the heart of Bangalore's tech scene, I've journeyed through the world of programming, leaving my mark one line of code at a time. Join me as I continue to explore, innovate, and push the boundaries of what's possible in the digital realm.

Related Posts

Automatically Launch Your Android App on Device Boot Using Java

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…

Secure File Transfer with Java: A Guide to SFTP

In today’s interconnected digital landscape, the need to securely transfer files between systems is ubiquitous. One of the most reliable and secure protocols for such transfers is…

Mastering Cron Expressions: A Comprehensive Guide

Cron expressions are a powerful tool that enables automation and task scheduling on Unix-like operating systems. Whether you’re a systems administrator, a developer, or simply someone interested…

Tables in Flutter PDF library

Hello Guys’ in this tutorial, I will teach you how to create a dynamically table in flutter pdf. I will use a plugin for this. Many times it happens…

CERTIFICATE_VERIFY_FAILED Error while performing a POST Request In Flutter

When Sending a post request in Dart. It is giving a response when We test it on API testing tools such as Postman. But when We run…

Android WebView With Downloading File

In this tutorial we will handle downloading files from WebView, The Android java code below can be used to download any type of files to your Android…

Leave a Reply

Your email address will not be published. Required fields are marked *