上篇文章我们学习了创建一个服务,startService、bindService,这篇文章写一下服务的生命周期和IntentService
startService的生命周期
context.startService()---->onCreate()---->onStartCommand()---->Service running---->context.stopService()---->onDestroy()---->Service stop
bindService的生命周期
context.startService()---->onCreate()---->onBind()---->Service running---->onUnbind()---->onDestroy()---->Service stop
IntentService
为了解决程序员忘记开启线程或者忘记调用stopSelf()方法,我们使用IntentService
1.IntentService是继承于MyIntentService并处理异步任务的一个类
2.在IntentService内有一个工作线程来处理耗时操作
3.会自动停止
用实例来看看他怎么用
1.先建一个MyIntentService继承自IntentService
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");//调用父类的 有参构造函数
}
//在这个方法中可以去处理一些具体的逻辑,而且不用担心ANR的问题,因为这个方法已经是在子线程中运行的了
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//打印当前线程的id
Log.d("MyIntentService", "Thread id is"+Thread.currentThread().getId());
}
//根据INtentService的特性,这个服务在运行结束后应该是会自动停止的,所以我们又重写了onDEstroy()方法
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}
}
2.定义一个布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lk.servicetest.MainActivity">
<Button
android:id="@+id/start_intent_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start IntentService"
android:textAllCaps="false" />
</LinearLayout>
3.修改MainActivity中的代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startIntentService= (Button) findViewById(R.id.start_intent_service);
startIntentService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_intent_service:
//打印主线程的id
Log.d("MainActivity", "Thread id is"+Thread.currentThread().getId());
Intent intentService=new Intent(this,MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}
}
4.在AndroidManifest.xml里注册
<service android:name=".MyIntentService" />