什么是IntentService,及其优点
IntentService是继承Service并处理异步任务的一个类;
在IntentService内有一个工作线程来处理异步耗时操作;
为Service的onBind()提供默认实现,返回null;为Service的onStartCommand提供默认实现;
与Service比较,IntentService不需要再创建新的线程,且多次调用线程会按顺序进行线程处理;
所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service;
IntentService只能用StartService来启动;
使用IntentService的步骤
新建类继承IntentService;
实现父类的构造方法;
重写onHandleIntent()方法;
重写onCreate方法;
重写onDesttory方法;
注册Service(容易忘记或出错)
在有Content的环境下启动Service
IntentService的使用实例
新建类继承IntentService;
重写onHandleIntent()方法;在这个方法中实现线程耗时操作;
重写onCreate方法;
package com.example.json;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by wang3 on 2018/3/23.
*/
public class MyIntentService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
}
public MyIntentService(){
super("");
}
@Override
public void onCreate() {
super.onCreate();
Log.e("1212121","onCreate");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
for (int i=0;i<=10;i++){
try {
Log.e("1212121",""+i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("1212121","onDestroy");
}
}
在Activity中启动IntentService
package com.example.json;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class WActivity extends AppCompatActivity implements View.OnClickListener{
private Button button;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_w);
button=findViewById(R.id.bind);
button2=findViewById(R.id.unbind);
button.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(WActivity.this, MyIntentService.class);
switch (v.getId()){
case R.id.bind:
startService(intent);
Log.e("111111","开始");
break;
case R.id.unbind:
stopService(intent);
Log.e("111111","结束");
break;
}
}
}