A, Android in IntentService
1.1 The main role
The implementation of a number of high-priority background task. Because it belongs Service, In terms than simply a higher priority thread.
1.2 Principle
IntentService encapsulates HandlerThread and a Handler.
- When you create a HandlerThread IntentService start, while Handler binding HandlerThread. Therefore messages sent by the Handler are performed in HandlerThread.
- Then IntentService into the life cycle of
onStartCommand
recallonStart
will be sent using the Intent object passed in the form of messages Handler. - Handler will be called after receiving the message
onHandleIntent
such an abstract method that we need to achieve their own processing logic. Finally processedstopSelf(msg.arg1);
wait for all tasks to complete end IntentService;
1.3 Features
Inherited Service, is an abstract class, you must create a subclass to use.
Two, IntentService use
Step 2.1 and examples
The following example uses two IntentService perform asynchronous tasks simultaneously broadcast schedule LocalBroadcastManager sent to inform the two tasks.
Layout two buttons (1) IntentServiceTestActivity for starting two tasks, two tasks are displayed ProgressBar. There is also a TextView for displaying Log.
(2) define a subclass IntentService, you must create a constructor name passed as a parameter of the worker threads IntentService. There are two examples for different processing task id and marked progress information. Concrete realization of the cycle count and increase timely sent to IntentServiceTestActivity updated UI.
public class IntentServiceTest extends IntentService {
...
// 必须创建该构造函数
public IntentServiceTest() {
super(IntentServiceTestActivity.TAG_MYINTENTSERVICE);
}
...
}
(3) IntentServiceTestActivity intent to start transmitting different IntentService through different buttons. Different parameters mark the task id.
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_task1:
Intent intentTask1 = new Intent(IntentServiceTestActivity.this,IntentServiceTest.class);
intentTask1.putExtra("taskId",0);
startService(intentTask1);
break;
case R.id.btn_task2:
Intent intentTask2 = new Intent(IntentServiceTestActivity.this,IntentServiceTest.class);
intentTask2.putExtra("taskId",1);
startService(intentTask2);
break;
}
}
(4) IntentServiceTest's onHandleIntent()
will hold messages of intent object, and then perform specific tasks.
// 实际处理任务
@Override
protected void onHandleIntent(@Nullable Intent intent) {
sendThreadStatus("IntentServiceTest开始处理 --> onHandleIntent()");
// intent已经通过IntentService内部的Handler传递过来
int taskId = intent.getIntExtra("taskId",0);
if(taskId == 0){
startThread(0);
} else {
startThread(1);
}
}
//根据不同的taskId来标记不同的进度
private void startThread(int taskId){
try {
Thread.sleep(1000);
//发送线程状态
sendThreadStatus("线程启动 --> startThread()");
boolean runnIng = true;
mProgress[taskId] = 0;
while (runnIng){
mProgress[taskId] ++;
if(mProgress[taskId] >= 100){
runnIng = false;
}
sendThreadStatus("线程Running --> startThread()");
Thread.sleep(30);
}
sendThreadStatus("线程结束 --> startThread()");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
...
(5) The above sendThreadStatus("")
method for transmitting broadcast by thread state:
/**
* 通过mLocalBroadcastManager发送IntentService的状态信息
* @param status
*/
private void sendIntentServiceStatus(String status) {
Intent intent = new Intent(IntentServiceTestActivity.ACTION_INTENTSERVICE_STATUS);
intent.putExtra("status",status);
mLocalBroadcastManager.sendBroadcast(intent);
}
/**
* 通过mLocalBroadcastManager发送工作线程的状态信息
* @param status
*/
private void sendThreadStatus(String status) {
Intent intent = new Intent(IntentServiceTestActivity.ACTION_THREAD_STATUS);
intent.putExtra("status",status);
intent.putExtra("progress",mProgress);
mLocalBroadcastManager.sendBroadcast(intent);
}
(6) IntentServiceTestActivity defined MyBroadcastReceiver received broadcast message update schedule further ProgressBar transmitted.
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()){
case ACTION_INTENTSERVICE_STATUS:
mInfoText.setText(mInfoText.getText().toString()+"\n"+intent.getStringExtra("status"));
break;
case ACTION_THREAD_STATUS:
int[] progress = intent.getIntArrayExtra("progress");
mProgressBar1.setProgress(progress[0]);
mProgressBar2.setProgress(progress[1]);
mPb1.setText(progress[0]+"%");
mPb2.setText(progress[1]+"%");
mInfoText.setText(intent.getStringExtra("status"));
break;
}
}
}
(7) Remember Register IntentService. <service android:name=".mythread.IntentServiceTest"/>
running result:
- Perform the same task twice in a row:
Click twice Task1.gif
- Continuously performs two tasks:
Click .gif two Task
We can see, whether it is how to add tasks are executed sequentially one by one. Once all the tasks finished IntentServiceTest executed onDestroy()
.
2.2 IntentService Caution
- IntentService not recommended
bindService()
manner, because IntentService of onBind default returns null. If it can communicate with Binder or Messenger, it is not invokedonHandleIntent()
method, IntentService just an ordinary Service a.
public IBinder onBind(Intent intent) {
return null;
}
- Once IntentService is stopped, which is stored in the message queue of tasks will be cleared, it will not be executed.
Related articles:
Android Multithreading: understand and use simple summary
Reprinted: https://www.jianshu.com/p/783015252b04