Android四大组件之服务Service(三)之IntentService

之前写过服务的基本使用https://blog.csdn.net/LJW874362735/article/details/100727663,不过服务(Service)的代码都是默认运行在主线程中的,如果要处理一些耗时任务,就会容易出现ANR(Application Not Responsing 没有响应)的情况,解决的方法就是使用Android的多线程技术,我们应该在服务的每个耗时任务开启子线程,如:

    ....
   @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
        
        new Thread(new Runnable(){
            //具体的耗时逻辑代码

            //但这种服务一旦启动就是一直运行,必须调用stopService(),或stopSeft()方法停止服务
            stopSeft();

    
        }).start();
    }
    ....

但这种服务一旦启动就是一直运行,必须调用stopService(),或stopSeft()方法停止服务,stopSeft(),会在执行完具体逻辑后自动关闭服务

写法不难,不过,平时不一定记得开启子线程,也不一定记得添加stopService(),或stopSeft()方法停止服务。

为了可以简单地创建一个异步的、会自动停止的服务,Android专门有IntentService

IntentService使用一般步骤:

①  新建一个类MyIntentService继承自IntentService:

public class MyIntentService extends IntentService {

    //首先需要一个无参构造函数,并调用父类有参构造函数
    public MyIntentService() {
        super("MyIntentService");
    }

    //重写,onHandleIntent(Intent intent),服务启动后会执行
    //具体耗时任务可以在这写,并且此方法的代码是运行在子线程中的
    @Override
    protected void onHandleIntent(Intent intent) {
        
        //具体的耗时逻辑代码
    }

    //服务停止后,会被执行
    @Override
    public void onDestroy(){
        super.onDestroy();
        
    }
}

●  首先需要一个无参构造函数,并调用父类有参构造函数,

●  然后重写onHandleIntent(Intent intent),具体耗时任务可以在这写,并且此方法的代码是运行在子线程中的

●  并且,IntentService特点,会在运行完相应的逻辑后,此服务会自动停止

②  启动IntentService:也是借助Intent,和startService(context, IntentService.class)

Intent intent= new Intent(context, 继承IntentService的类名.class);
startService( intent );

②  停止IntentService:在服务运行完后,会自动停止,不同调用什么方法

IntentService,好处就是,其方法protected void onHandleIntent(Intent intent)会在子线程中执行,并会自动停止

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值