Android Service详解-IntentService简介
IntentService 简介
IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 中存在一个工作线程来处理耗时操作,当任务执行完毕时,IntentService 会自动关闭,可以同时启动 IntentService 多次,每一个耗时操作会以队列的形式在 onHandleIntent 回调方法中顺序执行
IntentService 和 Service
IntentService 不需要手动创建子线程,不需要考虑 Service的关闭时间
IntentService 启动方式
和 Service 启动方式相同,具体可参照 Android Service详解-启动方式
IntentService 代码
Activity 代码
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button mBtn_StartService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtn_StartService = findViewById(R.id.btn_startService);
mBtn_StartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick: " + Thread.currentThread().getId());
MyIntentService.actionStart(MainActivity.this, "this's test data");
}
});
}
}
IntentService 代码
public class MyIntentService extends IntentService {
private static final String TAG = "MyIntentService";
public static void actionStart(Context context, String data){
Intent intent = new Intent(context, MyIntentService.class);
intent.putExtra("data", data);
context.startService(intent);
}
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if (intent != null){
String data = intent.getStringExtra("data");
Log.i(TAG, "onHandleIntent: " + Thread.currentThread().getId() + "; data : " + data);
}
}
}
Log 信息
I/MainActivity: onClick: 2
I/MyIntentService: onHandleIntent: 256; data : this's test data
I/MainActivity: onClick: 2
I/MyIntentService: onHandleIntent: 257; data : this's test data