1

I'm trying to recreate an activity at a certain time each day, e.g. 6am every morning.

Currently, my scheduled task is working, but instead of recreating my Activity once, it continuously recreates it, like it is stuck in a loop.

From my Main Activity I use:

 scheduledRefresh.setAlarm(this);

Then in my scheduled refresh:

 public void onReceive(Context context, Intent intent) {   
    Intent service = new Intent(context, ScheduledRefreshService.class);       
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, service);
}

//Alarm is set for a specific time each day
public void setAlarm(Context context) {
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, ScheduledRefresh.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    // The alarm is set for 6 am daily
    calendar.set(Calendar.HOUR_OF_DAY, 06);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);


    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,  
            calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);

    ComponentName receiver = new ComponentName(context, ScheduledBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);           
}

public void cancelAlarm(Context context) {
    // If the alarm has been set, cancel it.
    if (alarmMgr!= null) {
        alarmMgr.cancel(alarmIntent);
    }

    ComponentName receiver = new ComponentName(context, ScheduledBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}

This calls my scheduled refresh service, which has this code to recreate the Activity:

 protected void onHandleIntent(Intent intent) {
    //restart mainActivity
    Intent map = new Intent(MainActivity.getContext(),MainActivity.class);          
    map.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MainActivity.getContext().startActivity(map);
    ScheduledRefresh.completeWakefulIntent(intent);
}

However, as I mentioned, it just keeps restarting the Activity, rather than just once - which is how it needs to work.

I've been trying to sort this out for ages!

Cœur
  • 37,241
  • 25
  • 195
  • 267
matt
  • 285
  • 4
  • 17

0 Answers0