How to start an activity on a certain time?

我是研究僧i 提交于 2019-12-12 09:24:28

问题


This question might be related to this and this question, but unlike those question I want to start them on a specific time, (say 11:12:13 on 15/03/2014).

I am actually working on a project (SMS) that sends messages on a given time.


回答1:


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)




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/22343942/how-to-start-an-activity-on-a-certain-time

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