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

  1. Create a BroadcastReceiver that listens 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 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.

Additional Resources

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

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 *