IntentService and HandlerThread use and read the source code
Brief introduction
use
Source code analysis
Brief introduction
IntentService is a special service, generally used to perform a number of time-consuming tasks, acts like Thread, but more common thread, service system priority, not easily relative to be killed. So IntentService accurate, suitable to perform some of the more important background tasks.
While the thread HandlerThread is inherited, a special thread, generally used with IntentService used without alone.
use
MyIntentService.java
public class MyIntentService extends IntentService {
/**
* Is Running
*/
private boolean isRunning;
/**
*schedule
*/
private int count;
public MyIntentService() {
super("test");
}
/**
* 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);
}
@Override
protected void onHandleIntent(Intent intent) {
Logout.e("onHandleIntent"+intent.getStringExtra("name"));
try {
Thread.sleep(1000);
isRunning = true;
count = 0;
while (isRunning) {
count++;
if (count >= 100) {
isRunning = false;
}
Thread.sleep(50);
Logout.e ( "thread running ..." + count);
}
Zhengzhou Women's Hospital: http: //jbk.39.net/yiyuanzaixian/sysdfkyy/
} catch (InterruptedException e) {
e.printStackTrace ();
}
Logout.e ( "end task");
}
@Override
public void onDestroy() {
super.onDestroy();
Logout.e ( "thread end of the run ..." + count);
}
public static class Logout{
private static final String TAG = "Logout";
public static void e(String conent){
Log.d(TAG, "e: "+conent);
}
}
}
public classTestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
startService(new Intent(this, MyIntentService.class));
new Handler().post(new Runnable() {
@Override
public void run() {
// delay period, send a second message
Intent intent = new Intent(AsyncTaskActivity.this, MyIntentService.class);
intent.putExtra("name", "helloWorld");
startService(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// handlerThread.quit();
// unbindService(serviceConnection);
}
}
The above is a simple tutorial IntentService of. IntentService is an abstract class, so they need to achieve their own integration, there are two things to note.
To achieve their own class needs a constructor with no arguments
IntentService process is time consuming in operation onHandleIntent, intent here is startService of intent.
Source code analysis
We first look at oncreate of IntentService code
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
// Construct a IntentService, and start
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
// Use the looper HandlerThread a configuration handler, so that it may receive a message transmitted from the HandlerThread
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
HandlerThread the more noteworthy is the run method.
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Here the code is relatively simple, the process is basically constructed in a non-standard process Handler ui thread then will come Looper.loop (); entering the infinite loop. So HandlerThread after the end of use, we need to remember to call the quit method to stop an endless loop.
End concerned oncreate method, we have to focus on and look IntentServcie onStartCommand method of onstart
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Here you can see the advantage of the characteristics of each onStartCommand each startService will call onStartCommand, used to IntentService deliver the message. IntentService after receiving the message, it will call mServiceHandler will send out a message. Here the main role is to pass information to the main thread HandlerThread. So then, we look at specific implementation ServiceHandler.
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent ((Intent) msg.obj);
stopSelf(msg.arg1);
}
}
Important code, of a total of two sentences, and onHandleIntent is what we need to override the method in IntentService own implementation, which is the method used to deal with time-consuming event.
If onHandleIntent after the event finished processing, service will attempt to call stopSelf to end off the entire service. But this is not the end of the service a mandatory operation, if the service is still unprocessed events, it would not end off. Not here in careful study, we remember this conclusion on the line.
And because the message blocking mechanism handler, the event here and will not be executed concurrently, but a single task similar SingleThreadExecutor serial execution.