AlarmManager 闹钟服务
一.闹钟服务流程
1.0.AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 获得系统提供的AlarmManager服务的对象
1.1.Intent设置要启动的组件: Intent intent = new Intent(MainActivity.this, SecondActivity.class);
1.3.PendingIntent对象设置动作,启动的是Activity还是Service,又或者是广播!
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0); 注意: a.获取的是getActivity、getService、getBroadcast b.假如你用的是alarmManager发送广播,广播再激活Activity的话, 则需要为Intent设置一个flag: intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1.4.调用AlarmManager的set( )方法设置单次闹钟的闹钟类型,启动时间以及PendingIntent对象
alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), pi); 注意: a.set(int type,long startTime,PendingIntent pi):一次性闹钟 b.setExact(int type, long triggerAtMillis, PendingIntent operation): 在规定的时间精确的执行闹钟,比set方法设置的精度更高 c.setRepeating(int type,long startTime,long intervalTime,PendingIntent pi): 重复性闹钟,和3有区别,3闹钟间隔时间不固定 d.cancel(PendingIntent pi): 取消AlarmManager的定时服务
二.举个栗子……
2.0. 实例每天23:59:00 闹钟
import java.util.Calendar; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { AlarmManager alarmManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Intent intent = new Intent(); intent.setClassName("com.gatsby.networktime", "com.gatsby.networktime.SecondActivity"); intent.putExtra("msg", "helloWorld"); // 当前系统 时间戳 long systemTime = System.currentTimeMillis(); Log.d("gatsby", "systemTime->" + System.currentTimeMillis()); // 闹钟 时间戳 long alarmTime = calendar.getTimeInMillis(); Log.d("gatsby", "alarmTime->" + calendar.getTimeInMillis()); if (systemTime > alarmTime) { // 如果设置的时间小于当前时间,闹钟时间 将添加一天,即明天 calendar.add(Calendar.DAY_OF_YEAR, 1); alarmTime = calendar.getTimeInMillis(); Log.d("gatsby", "alarmTime2->" + calendar.getTimeInMillis()); } PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0); // 重复每天提醒 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, AlarmManager.INTERVAL_DAY, pi); Log.d("gatsby", "alarmTime.setRepeating->" + calendar.getTimeInMillis()); } }
2.1.取消闹钟
alarmManager.cancel(pi);