Search code examples
javaandroidbroadcastreceiverstartup

How to make an app to run automatically on startup with delay?


I made my app on Stratup with this permission

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

and adding this to my AndroidManifast.xml

        <receiver android:enabled="true" android:name=".BootUpReceiver" 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>

And this in my java codes:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootUpReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, Main.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

}

When app starts on startup, it crashes and when I strat it again it works carefully. I don't know what its cause is. So I decided to start it with some delay to solve this problem.I want your help to add delay.


Solution

  • I had a similar requirement to start a service after system boot with a delay. I added the delay to the receiver as below. Rest of your code looks fine.

    public void onReceive(final Context context, Intent intent) {
    
        // We can't wait on the main thread as it would be blocked if we wait for too long
        new Thread(new Runnable() {
    
            @Override
            public void run() {
                try {
                    // Lets wait for 10 seconds
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    Log.e(TAG, e.getMessage());
                }
    
                // Start your application here
            }
        }).start();
    }
    

    Here I have started a new Thread with a 10 second delay that would start the application or service after the delay.

    Reference link: https://github.com/midhunhk/message-counter/blob/master/v2/MessageCounter/src/com/ae/apps/messagecounter/receivers/BootCompletedReceiver.java