美文网首页Android 开发精要系列文章
AlarmManager 系统服务的开发精要

AlarmManager 系统服务的开发精要

作者: ahking17 | 来源:发表于2017-08-28 10:40 被阅读68次
    使用目的

    目的: 简单一句话就是它可以发送一个PendingIntent出来.
    使用AlarmManager可以实现定时发送一个PendingIntent出来, 如果这个PendingInteng封装的是一个广播类型的intent对象, 那么就可以让监听这个广播类型的BroadcastReceiver的onReceive() 定时被执行某些特定的操作.

    典型应用场景是, 在天气app的开发中, 定时更新天气数据(从网上拉取数据, 并解析数据, 把结果存入数据库的操作)的功能就是利用AlarmManager来完成的.

    代码

    AlarmManager 是一个系统级的服务, 获取这个服务的方法是:

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    

    使用它的目的就是通过调用它的API( eg. setRepeating() ), 定时向系统发送一个PendingIntent对象出来.

    PendingIntent本质上来说, 就是对intent的一个包装, 如果这个PendingIntent对象是通过PendingIntent.getBroadcast()获取到的, 那么当PendingIntent对象发送出来后, 系统会自动调用sendBroadcast(intent), 发送它里面封装的intent广播对象. 这个广播对象所对应的BroadcastReceiver的onReceive()方法就会被定期的执行.

    public class AutoUpdateService extends Service {
        public static final String ACTION_BACKGROUND_UPDATE = "com.hola.weather.action_background_update";
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            BackgroundUpdateReceiver backgroundUpdateReceiver = new BackgroundUpdateReceiver();
            registerReceiver(backgroundUpdateReceiver, new IntentFilter(ACTION_BACKGROUND_UPDATE));
    
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent intent = new Intent(ACTION_BACKGROUND_UPDATE);
            pendingIntent = PendingIntent.getBroadcast(AutoUpdateService.this, 0, intent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + getCurrentUpdateInterval(), getCurrentUpdateInterval(), pendingIntent);
        // API: setRepeating(int type,long startTime,long intervalTime,PendingIntent pendingIntent);
    
        }
    
        private class BackgroundUpdateReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
            //执行从网上拉取数据, 并解析数据, 把结果存入数据库的操作
        }
        }
    
    }
    

    refer to:
    http://blog.csdn.net/wangxingwu_314/article/details/8060312

    ---DONE.------

    相关文章

      网友评论

        本文标题:AlarmManager 系统服务的开发精要

        本文链接:https://www.haomeiwen.com/subject/jemwdxtx.html