Start app at a specific time

前端 未结 3 1208
不知归路
不知归路 2020-11-29 01:30

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 wan

3条回答
  •  孤独总比滥情好
    2020-11-29 02:20

    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));
       }
    }
    

提交回复
热议问题