TiGer TiGer - 1 month ago 9
Android Question

Start app at a specific time

I was wondering if it's possible (and if it is how) to start up my app at a specific time, something like an alarmclock which goes off at a specific time.
Let's say I want my app to start up at 8 in the morning, is that feasable ?

Answer

You can do it with AlarmManager, heres a short example. First you need to set the alarm:

        AlarmManager am = (AlarmManager) con
            .getSystemService(Context.ALARM_SERVICE);

    Date futureDate = new Date(new Date().getTime() + 86400000);


    futureDate.setHours(8);
    futureDate.setMinutes(0);
    futureDate.setSeconds(0);


    Intent intent = new Intent(con, MyAppReciever.class);

    PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    am.set(AlarmManager.RTC_WAKEUP, futureDate.getTimeInMillis(), sender); 

Next, You need to create a reciever with some code to execute your application: (ie- starting your app):

public class MyAppReciever extends BroadcastReceiver {

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

    startActivity(new Intent(context, MyAppMainActivity.class));
   }
}
Comments