初识IntentService

服务中的代码,都是默认运行在主线程当中的,如果要进行耗时操作,一般我们会选择在onStartCommand里面写一个子线程,但是这种服务一旦启动就会一直运行,必须手动调用stopService或者stopSelf方法服务才会停止,为了创建一个异步的,会自动停止的服务,Android专门提供了一个IntentService类:

An {@link IntentService} subclass for handling asynchronous task
requests in a service on a separate handler thread.

package com.jackie.servicetest;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {


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

    @Override
    protected void onHandleIntent(Intent intent) {
        //打印当前线程id
        Log.d("jackie","Service的线程Id为:"+Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        Log.d("jackie","onDestroy executed");


    }
}
package com.jackie.servicetest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("jackie", "主线程的Id是:" + Thread.currentThread().getId());
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, MyIntentService.class);
                startService(intent);

            }
        });
    }
}
11-25 21:58:29.630 18201-18201/? D/jackie: 主线程的Id是:1
11-25 21:58:46.890 18201-18218/? D/jackie: Service的线程Id为:240
11-25 21:58:46.890 18201-18201/? D/jackie: onDestroy executed

可以看到,执行完逻辑后IntentService自动执行了onDestroy

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值