Java – Simple AlarmManager example to trigger an activity within 10 minutes

Simple AlarmManager example to trigger an activity within 10 minutes… here is a solution to the problem.

Simple AlarmManager example to trigger an activity within 10 minutes

I’ve found a lot of issues similar to this, but they’re too complicated (too much code), at least I think so.

Can this thing be done with a few lines of code? I want to start an activity in 10 (assuming) minutes and that’s it. Thank you.

Solution

Set an alarm for 10 minutes (let’s say) Use this code

 AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
 Intent intent = new Intent(this, ShortTimeEntryReceiver.class);   
 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
 alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),10*60*1000, pendingIntent); 

Start the activity

public class ShortTimeEntryReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {

try {
         Bundle bundle = intent.getExtras();
         String message = bundle.getString("alarm_message");

 Your activity name
         Intent newIntent = new Intent(context, ReminderPopupMessage.class); 
         newIntent.putExtra("alarm_message", message);
         newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
         context.startActivity(newIntent);
        } catch (Exception e) { 
         e.printStackTrace();

} 
} 
}

Add the following to your list file

 <receiver android:name=". ShortTimeEntryReceiver"
                      android:enabled="true"
                      android:process=":remote"> 
            </receiver>

Related Problems and Solutions