服务中的代码,都是默认运行在主线程当中的,如果要进行耗时操作,一般我们会选择在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