Android IntentService

  1. 创建服务
    新建一个继承IntentService的class,如下
public class SelfService extends IntentService {

    public static final String TAG="SelfService ";

    public static Intent newIntent(Context context){
        return new Intent(context,PollService.class);
    }

    public SelfService () {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG,"Received an intent: "+intent);
        //在这里做一些需要在后台干的事,比如检查网络连接,定义重新连接,或者别的什么事情
    }
}

首先创建构造方法。然后覆盖IntentService的onHandlerIntent()方法。
再创建静态内部类,用来创建intent对象。

  1. 启动服务
    可以在fragment的onCreate()方法中调用服务。通过创建intent对象,并调用context的startService()来完成。
    启用语句:
Intent intent=SelfService.newIntent(getActivity());
getActivity.startService(intent);
  1. 没有托管Fragment的Activity时,如何启动服务?
    可以使用AlarmManager,AlarmManager本身是一个系统服务,它本身可以发送Intent。
    我们可以通过PendingIntent打包一个要启动某个后台服务的Intent,然后将其发送给AlamManager。
    AlarmManager通过setRepeating()方法来启动定时的循环。
    代码:
//创建Intent
Intent intent=SelfService.newIntent(context);
//创建一个打包了Intent的PendingIntent,pendingIntent包含四个参数:
//一个用来发送intent的context,区分pendingIntent来源的请求代码,一个待发送的intent实体,以及
//一组用来决定如何创建PendingIntent的标识符。
PendingIntent pi=PendingIntent.getService(context,0,intent,0);
//获取系统服务
AlarmManager alarmManager=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//设置重复时间
alarmManager.setRepeating(AlarmManager.ELAPSED_REATIME,SystemClock.elapsedRealtime(),POLL_INTERVAL, pi);

4.取消定时器
用alarmManager.cancel(PendingIntent pi)取消,通常需要同步取消PendingIntent。

程序首次运行后,后台就启动定时器,即使程序进程停止了,AlarmManager依然会不断的发送Intent,反复启动指定的服务 。

注意:如果不停止定时器,会一直在后台运行。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转载请注明出处:http://www.jianshu.com/p/95e0ef1b81cb[https://www...
    朋永阅读 1,428评论 2赞 10
  • 序言 最近有用到IntentService,对IntentService的源码做了一定的学习,所以今天来谈谈我对i...
    瘦竹竿阅读 1,016评论 2赞 6
  • 简介 服务 是 Android 应用的后台。 服务 可以不依赖Activity独自生存。 直接使用Service创...
    iDragonfly阅读 448评论 0赞 0
  • 美如画 什么时候都不要忘了爱自己
    美_b96a阅读 124评论 0赞 0
  • 生命中的热爱也叫生活中的兴趣爱好,以前总觉得要啥兴趣爱好,吃好,喝好,该学的时候学,该玩的时候玩得了。。。时间长了...
    可可西里有可乐阅读 285评论 0赞 2

友情链接更多精彩内容