Reputation: 1066
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.
Upvotes: 2
Views: 2182
Reputation: 824
I would start an IntentService from the broadcast receiver and achieve the delay by sleeping inside onHandleIntent() before performing the heavy processing.
The other answer suggests creating a thread from the broadcast receiver and sleeping there. My concern with that approach is that the receiver object will die leaving the App without any application components (activity,service, receiver) meaning the OS may be more likely to kill the process than in the situation where there is a live service. Having said that, I am guessing anyway Android won't kill the process at this time because the system is just booting up and normally there should be enough resources available, however, the service approach seems to be more in the Android's spirit.
Upvotes: 0
Reputation: 5554
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
Upvotes: 4