IntentService

IntentService是Service的子类,和 Service 不同的是 IntentService 自带一个子线程,该子线程支持消息消息循环,Service 中的所有耗时任务都可以放到该子线程中来完成。该子线程使用的 HandlerThread 类型,是一个带 Looper 的可以关联 handler 的线程。IntentService 自带的 handler 是 ServiceHandler。在 Service 的 onCreate 中创建的该 thread,在 Service 的 onDestroy 中通过 looper 的 quit 方法结束线程。

1.IntentService特征

有独立的 worker 线程来处理 Intent 请求,默认 handler 会调用onHandleIntent() 方法来处理;
所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service;
为Service的onBind()提供默认实现,返回null;
为Service的onStartCommand提供默认实现,将请求Intent封装成了消息,让 ServiceHandler 调用 onHandlerIntent 方法在子线程中来处理;

2.使用步骤

1.继承IntentService类,并重写onHandleIntent()方法

MyIntentService.java

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("----onCreate---");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // IntentService会使用单独的线程来执行该方法的代码
        // 该方法内执行耗时任务,比如下载文件,此处只是让线程等待20秒
        long endTime = System.currentTimeMillis() + 20 * 1000;
        System.out.println("onStart");
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("----耗时任务执行完成---");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("----onDestroy---");
    }
}

2.通过 startService 调用 Service 功能

MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.intentService:
                Intent intent = new Intent(this, MyIntentService.class);
                startService(intent);
                break;
            case R.id.service:

                break;
            default:
                break;
        }
    }

}

3.在 AndroidManifest.xml 中注册 Service

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值