简介:

关于service 大家应都知道是Android 四大组件之一,用来执行后台任务的。Android 中的定时任务一般有两种实现方式,一种是使用Java API 里提供的Timer 类,一种是使用Android 的Alarm 机制。那么首先我们来看一下Alarm 机制的用法吧, 其实并不复杂, 主要就是借助了AlarmManager 类来实现的。这个类和NotificationManager 有点类似,都是通过调用Context 的getSystemService()方法来获取实例的,只是这里需要传入的参数是Context.ALARM_SERVICE。因此,获取一个AlarmManager 的实例就可以写成:AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);接下来调用AlarmManager 的set()方法就可以设置一个定时任务了,比如说想要设定一个任务在10 秒钟行,就可以写成:long triggerAtTime = SystemClock.elapsedRealtime() + 10 * 1000;  manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);上面的两行代码你不一定能看得明白,因为set()方法中需要传入的三个参数稍微有点复杂,下面我们就来仔细地分析一下。第一个参数是一个整型参数,用于指定AlarmManager 的工作类型,有四种值可选,分别是ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC 和RTC_WAKEUP。其中ELAPSED_REALTIME 表示让定时任务的触发时间从系统开机开始算起,但不会唤醒CPU。ELAPSED_REALTIME_WAKEUP 同样表示让定时任务的触发时间从系统开机开始算起,但会唤醒CPU。RTC 表示让定时任务的触发时间从1970 年1月1 日0 点开始算起,但不会唤醒CPU。RTC_WAKEUP 同样表示让定时任务的触发时间从1970 年1 月1 日0 点开始算起,但会唤醒CPU。使用SystemClock.elapsedRealtime()方法可以获取到系统开机至今所经历时间的毫秒数,使System.currentTimeMillis()方法可以获取到1970 年1 月1 日0 点至今所经历时间的毫秒数。然后看一下第二个参数,这个参数就好理解多了,就是定时任务触发的时间,以毫秒为单位。如果第一个参数使用的是ELAPSED_REALTIME 或ELAPSED_REALTIME_WAKEUP,则这里传入开机至今的时间再加上延迟执行的时间。如果第一个参数使用的是RTC 或RTC_WAKEUP,则这里传入1970 年1 月1 日0 点至今的时间再加上延迟执行的时间。第三个参数是一个PendingIntent,对于它你应该已经不会陌生了吧。这里我们一般会调用getBroadcast()方法来获取一个能够执行广播的PendingIntent。这样当定时任务被触发的时候,广播接收器的onReceive()方法就可以得到执行。了解了set()方法的每个参数之后,你应该能想到,设定一个任务在10 秒钟后执行还可以写成:long triggerAtTime = System.currentTimeMillis() + 10 * 1000;manager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pendingIntent);好了,现在你已经掌握Alarm 机制的基本用法,下面我们就来创建一个可以长期在后台执行定时任务的服务

定时任务实现:

AlarmReceiver

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class AlarmReceiver extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent intent) {    Intent i = new Intent(context,LongRunningService.class);        context.startService(i);    }}

LongRunningService

import android.app.AlarmManager;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import android.support.annotation.Nullable;import android.util.Log;import java.util.Date;public class LongRunningService extends Service {    private static final String TAG = "LongRunningService";    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        new Thread(new Runnable() {            @Override            public void run() {                Log.i(TAG, "run: executed at "+new Date().toString());            }        }).start();    AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);    int anHour = 60*1000;    long triggerAtTime = SystemClock.elapsedRealtime()+anHour;    Intent i = new Intent(this,AlarmReceiver.class);    PendingIntent pi = PendingIntent.getBroadcast(this,0,i,0);manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);    return super.onStartCommand(intent, flags, startId);    }}

MainActivity

import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Intent intent = new Intent(this,LongRunningService.class);        startService(intent);    }}

manifest.xml

更多相关文章

  1. mybatisplus的坑 insert标签insert into select无参数问题的解决
  2. Python技巧匿名函数、回调函数和高阶函数
  3. python list.sort()根据多个关键字排序的方法实现
  4. android中文api(89)——ViewManager
  5. Android调用天气预报的WebService简单例子
  6. Android(安卓)Activity的启动
  7. 修改android系统和watchdog的延时
  8. Android(安卓)之 AsyncTask 异步任务
  9. Android(安卓)任务和回退堆栈---启动任务

随机推荐

  1. Linux运维教程-Linux系统远程配置
  2. Linux运维教程-Linux系统网络管理
  3. Linux运维教程-Linux服务进程管理
  4. Java文件上传是如何实现的?
  5. Linux运维教程-Linux软件包管理
  6. php的初步认识与常用数据类型
  7. JQuery初学习之`$()`的参数类型
  8. 如何使用 Apple Configurator 2 修复或恢
  9. jenkins打包上传oss
  10. 记一次服务器负载过高的排查过程