阅读更多

虽然alarm的意思是闹钟,而且在原生android自带的闹钟应用中AlarmManager也确实非常重要,但并不代表AlarmManager只是用来做闹钟应用的,作为一个一种系统级别的提示服务,肯定应该有着非常重要的地位,实际上android中很多东西都可以利用AlarmManager来实现。

AlarmManager在特定的时刻为我们广播一个指定的Intent。简单的说就是我们设定一个时间,然后在该时间到来时,AlarmManager为我们广播一个我们设定的Intent。这个intent可以指向一个activity,也可以指向一个service。

下面就是使用alarm定时调用service实现轮询的实现方法:

一、新建轮询工具类PollingUtils.java

 

public class PollingUtils {    //开启轮询服务    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();                                                                                                                                                                                                                                               //使用AlarmManger的setRepeating方法设置定期执行的时间间隔(seconds秒)和需要执行的Service        manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtTime,                seconds * 1000, pendingIntent);    }    //停止轮询服务    public static void stopPollingService(Context context, Class<?> cls,String action) {        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);    }}

 二、构建轮询任务执行PollingService.java

 

 

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 配置

 

 

                                                        

 四、在MainActivity.java中开启和停止PollingService

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, 5, PollingService.class, PollingService.ACTION);    }                                                                                                                                                                                                                       @Override    protected void onDestroy() {        super.onDestroy();        //Stop polling service        System.out.println("Stop polling service...");        PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);    }}

 

 

更多相关文章

  1. xamarin Android(安卓)activity生命周期详解
  2. Android基本组件学习(Activity生命周期)
  3. Android中AsyncTask的简单用法
  4. Android兼容性测试工具Spoon
  5. Android中线程形态AsyncTask、HandlerThread 和 IntentService简
  6. Android(安卓)Framework入门介绍
  7. android 中http请求的容错管理
  8. Android使用xutils3框架实现应用程序内的检查更新下载服务器存放
  9. android 中关于 activity 的一些理解

随机推荐

  1. android增加5G热点
  2. android权限设置
  3. Android地图添加标记和文字【代码片段】
  4. ubuntu系统下,搭建Android开发环境!!
  5. Android编译源码时出现的错误: “_FORTIFY
  6. 【Android(安卓)UI】状态栏和toolbar颜色
  7. Android面试总结(持续更新)
  8. 面试题5:椭圆里面有个内切圆,内切圆中有文
  9. Android(安卓)点击back键两次退出程序
  10. Android中ps命令各字段的含义