How to start an activity on a certain time?

偶尔善良 提交于 2019-12-04 19:39:55

try this code, I tested it:

First: Create a calendar:

Calendar calendar = Calendar.getInstance();
  • And set time by one of this ways:

    calendar.set(year, month, day, hourOfDay, minute);
    // be careful month start form "0" so for "May" put "4"
    
  • or:

    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    

Second: Add this:

Intent intent = new Intent(MainActivity.this, NextActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Note: If you need a timer, you can replace alendar.getTimeInMillis() to System.currentTimeMillis() + x in above code. (x is an int of milliseconds that you want make wait)

Vishal Santharam

Use AlarmManager from the Android API. Just follow this tutorial:

http://android-er.blogspot.in/2011/05/using-alarmmanager-to-start-scheduled.html.

In the above tutorial, they talk about scheduling the activity after some interval. In your case, just take the difference between the current time and your time to launch and explore the API to get what you want.

If you want to start Activity on a cretaion time use AlarmManager.

I write a example for this.

Intent intent = new Intent(this, YourReceiver.class);

//11:12:13 on 15/03/2014 

Calendar cal=Calendar.getInstance();
cal.set(Calendar.MONTH,2);//because is started from 0
cal.set(Calendar.YEAR,2014);
cal.set(Calendar.DAY_OF_MONTH,15);
cal.set(Calendar.HOUR_OF_DAY,11);
cal.set(Calendar.MINUTE,12);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);



alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent );

inside your receiver call to activity using Contect.startActivity method. Don't forget to register receiver inside your meanifest.xml.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!