
Android检测冲突摘要
Android 3D特殊效果源代码摘要

类似Siri的中文语音助手源代码
AlarmManager使用某些机制作为全局计时器,另一些机制用作闹钟. 通过使用它,我个人觉得将其称为全局计时器更为合适. 实际上,它的作用与Timer类似. 有两种类似的用法: (1)在指定的持续时间后执行操作(2)定期执行操作

AlarmManager对象与Intent一起使用,您可以定期打开活动,发送BroadCast或启动服务.
以下代码详细介绍了两种计时方法的使用:

(1)在指定的持续时间后执行操作
//操作:发送一个广播,广播接收后Toast提示定时操作完成 Intent intent =new Intent(Main.this, alarmreceiver.class); intent.setAction("short"); PendingIntent sender= PendingIntent.getBroadcast(Main.this, 0, intent, 0); //设定一个五秒后的时间 Calendar calendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 5); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); //或者以下面方式简化 //alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, sender); Toast.makeText(Main.this, "五秒后alarm开启", Toast.LENGTH_LONG).show();

注意: 接收者记得在manifest.xml中注册
public static class alarmreceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if(intent.getAction().equals("short")){ Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(context, "repeating alarm", Toast.LENGTH_LONG).show(); } } }
(2)定期执行操作
Intent intent =new Intent(Main.this, alarmreceiver.class); intent.setAction("repeating"); PendingIntent sender=PendingIntent .getBroadcast(Main.this, 0, intent, 0); //开始时间 long firstime=SystemClock.elapsedRealtime(); AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE); //5秒一个周期,不停的发送广播 am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP , firstime, 5*1000, sender);
AlarmManager的setRepeating()等同于Timer的Schedule(任务android 全局定时器android 全局定时器,延迟,周期);当差异很小时,Timer的方法是指定开始定期执行任务后要延迟多长时间. 请注意,已取消的Intent必须与启动Intent完全一致,以支持AlarmManager的取消)
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-229766-1.html
我们不嫌她老