新建一个Service来模拟后台执行的程序,PollingService.java:
package com.ryantang.rtpollingdemo; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * Polling service * @Author Ryan * @Create 2013-7-13 涓婂崍10:18:44 */ public class PollingService extends Service { public static final String ACTION = "com.ryantang.service.PollingService"; private Notification mNotification; private NotificationManager mManager; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { initNotifiManager(); } @Override public void onStart(Intent intent, int startId) { new PollingThread().start(); } //初始化通知栏配置 private void initNotifiManager() { mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); int icon = R.drawable.ic_launcher; mNotification = new Notification(); mNotification.icon = icon; mNotification.tickerText = "New Message"; mNotification.defaults |= Notification.DEFAULT_SOUND; mNotification.flags = Notification.FLAG_AUTO_CANCEL; } //弹出Notification private void showNotification() { mNotification.when = System.currentTimeMillis(); //Navigator to the new activity when click the notification title Intent i = new Intent(this, MessageActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK); mNotification.setLatestEventInfo(this, getResources().getString(R.string.app_name), "You have new message!", pendingIntent); mManager.notify(0, mNotification); } /** * Polling thread * 模拟向Server轮询的异步线程 * @Author Ryan * @Create 2013-7-13 涓婂崍10:18:34 */ int count = 0; class PollingThread extends Thread { @Override public void run() { System.out.println("Polling..."); count ++; //当计数能被5整除时弹出通知 if (count % 5 == 0) { showNotification(); System.out.println("New message!"); } } } @Override public void onDestroy() { super.onDestroy(); System.out.println("Service:onDestroy"); } }
别望了在AndroidManifest.xml中注册Service:
<service android:name="com.ryantang.rtpollingdemo.PollingService"> <intent-filter> <action android:name="com.ryantang.service.PollingService"/> </intent-filter> </service>
当计数能被5整除时弹出通知,点击通知后进入MessageActivity.java:
package com.ryantang.rtpollingdemo; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.os.Bundle; public class MessageActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); System.out.println("新的activity"); NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); manager.cancelAll(); } }
使用AlarmManager封装已给PollingUtils.java来执行Service的启动和停止,PollingUtils.java:
package com.ryantang.rtpollingdemo; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.SystemClock; /** * Polling Tools * @Author Ryan * @Create 2013-7-13 涓婂崍10:14:43 */ public class PollingUtils { /**开启轮询服务 * @param context * @param seconds 定期执行的时间间隔 * @param cls * @param action */ public static void startPollingService(Context context, int seconds, Class<?> cls,String action) { //获取AlarmManager系统服务 AlarmManager manager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); //包装需要执行Service的Intent Intent intent = new Intent(context, cls); intent.setAction(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); //触发服务的起始时间 long triggerAtTime = SystemClock.elapsedRealtime(); //使用AlarmManager的setRepeating方法设置定期执行时间间隔(seconds秒)和需要执行的Service manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtTime, seconds * 1000, pendingIntent); } /** * 停止轮询服务 * @param context * @param cls * @param action */ public static void stopPollingService(Context context, Class<?> cls,String action) { //获取AlarmManager系统服务 AlarmManager manager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, cls); intent.setAction(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); //取消正在执行的服务 manager.cancel(pendingIntent); } }
最后在主程序中执行,MainActivity.java:
package com.ryantang.rtpollingdemo; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Start polling service System.out.println("Start polling service..."); PollingUtils.startPollingService(this, 30, PollingService.class, PollingService.ACTION);// PollingService.ACTION与AndroidManifest.xml一一对应 } @Override protected void onDestroy() { super.onDestroy(); // Stop polling service System.out.println("Stop polling service..."); PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION); } }
Android之AlarmManager(全局定时器/闹钟)指定时长或以周期形式执行某项操作
(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);
//注意:receiver记得在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(); } } }
<receiver android:name="" > <intent-filter > <action android:name="short"><action /> </intent-filter> </receiver>
AlarmManager类型如下:
AlarmManager.RTC,硬件闹钟,不唤醒手机(也可能是其它设备)休眠;当手机休眠时不发射闹钟。
AlarmManager.RTC_WAKEUP,硬件闹钟,当闹钟发射时唤醒手机休眠;
AlarmManager.ELAPSED_REALTIME,真实时间流逝闹钟,不唤醒手机休眠;在指定的延时过后,发送广播,但不唤醒设备。
AlarmManager.ELAPSED_REALTIME_WAKEUP,真实时间流逝闹钟,当闹钟发射时唤醒手机休眠;
RTC闹钟和ELAPSED_REALTIME最大的差别就是前者可以通过修改手机时间触发闹钟事件,后者要通过真实时间的流逝,即使在休眠状态,时间也会被计算。
(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(task,delay,peroid);有点差异的地方时Timer这个方法是指定延迟多长时间以后开始周期性的执行task;
AlarmManager的取消:(其中需要注意的是取消的Intent必须与启动Intent保持绝对一致才能支持取消AlarmManager)
Intent intent =new Intent(Main.this, alarmreceiver.class); intent.setAction("repeating"); PendingIntent sender=PendingIntent .getBroadcast(Main.this, 0, intent, 0); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.cancel(sender);
时间: 2024-10-12 23:21:44