charlest
charlest

Reputation: 935

How to set a timed event which will keep running even if the application is stopped

I need to have a process run whenever the end-user clicks on a Submit button. The application needs to try to process the data on the screen every X minutes, Y times, even if the the application is down. So, it will need to attempt to do some processing until one of the following occurs: 1) The processing is successful for the data that was submitted 2) The processing has been retried Y times and still never succeeded 3) The application is terminated by the OS or the phone is turned off.

If the end-user's phone is still on but the application has stopped, what's the correct interface to use to accomplish this?

If I use Handler/Runnable, that only works as long as the application stays active. AlarmManager looks like it's used when you want processing to run at a specific time.

Any suggestions will be greatly appreciated!

Upvotes: 1

Views: 1593

Answers (3)

FoamyGuy
FoamyGuy

Reputation: 46856

I use this method to set an alarm.

private void setAlarm(){
    Context context = getApplicationContext();
    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, OnAlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);

    myCal = Calendar.getInstance();
    myCal.setTimeInMillis(myPrefs.getLong("time", 0));

    mgr.set(AlarmManager.RTC_WAKEUP, myCal.getTimeInMillis(), pi);
    Log.i(myTag, "alarm set for " + myCal.getTime().toLocaleString());
    Toast.makeText(getApplicationContext(),"Alarm set for " + myCal.getTime().toLocaleString(), Toast.LENGTH_LONG).show();

}

inside my onAlarmReciever onRecieve method is this:

        Intent i = new Intent(context, AlarmActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

So basically when the intent fires it starts the AlarmActivity. Inside that activity you could have it try what ever you are doing and if it fails call the setAlarm() again

Upvotes: 2

Aleadam
Aleadam

Reputation: 40401

You have two options: a Service, or set up an alarm with AlarmManager. Which one you pick will depend mostly how often do you want to retry. A minute? Use a service. An hour? A day? set up an alarm so you don't waste the phone resources keeping the service alive.

http://developer.android.com/reference/android/app/Service.html

http://developer.android.com/reference/android/app/AlarmManager.html

Upvotes: 1

Mike Marshall
Mike Marshall

Reputation: 7850

Write an Android Service

Upvotes: 0

Related Questions