Reputation: 1
I have a broadcast receiver and I want to initiate another activity/service using an alarm manager. So I want to set an alarm manager in my broadcast receiver to start the activity dynamically. Is it possible. Please tell guide me accordingly. Thanks
Upvotes: 0
Views: 1294
Reputation: 9870
Do You want to Show us a Little bit of Your code? We can´t exactly answer if You do not explain a bit more. But starting activity from broadcast Receiver is just simple as starting activity in the usual way:
Intent intent = new Intent(context.getApplicationContext(), YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Use this in Your onReceive()....and don´t Forget to Register Your Receiver to the manifest.
So if You want to start an Action 5 minutes after reboot, it should be something like this:
start another boradcastreceiver in Your BootCompleted Receiver:
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,SecondBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 300000, pendingIntent); //5 minutes are 300000 MS
public class SecondBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i= new Intent(context, YourService.class);
context.startService(i);
}
}
public class YourService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//start here the Action You will do, 5 minutes after reboot
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
But this is only from scratch, I can´t test the code for now, have no IDE here. So I am not sure about givin the context to Intent and PendingIntent in Your BootCompletedReceiver.
Upvotes: 1