IntentService is a subclass of Service that adds additional functionality over regular Service. There are two problems with the Service itself:
-
A Service does not start a separate process. A Service is in the same process as its application.
-
A Service is not dedicated to a new thread, so time-consuming tasks should not be handled directly within the Service;
2. IntentService Features
-
A separate worker thread is created to handle all Intent requests;
-
A separate worker thread is created to handle the code that implements the onHandleIntent() method without having to deal with multithreading;
-
IntentService stops automatically after all requests are processed, without calling stopSelf() to stop the Service;
-
Provide a default implementation for Service onBind(), which returns NULL;
-
Provide a default implementation for Service onStartCommand that adds the Intent to the queue.
Iii. Use steps (Please refer to Service project for details)
-
Inherit the IntentService class and override the onHandleIntent() method.
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent Intent = new Intent(this, myservice.class);} public void startService(View source) {// Create an Intent(this, myservice.class); startService(intent); } public void startIntentService(View source) {// Create an IntentService Intent Intent = new Intent(this, MyIntentService.class); startService(intent); }}
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @override protected void onHandleIntent(Intent Intent) {// IntentService uses a separate thread to execute its code. Long endTime = System.currentTimemillis () + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); }} system.out. println("---- time-consuming task executed --"); }}
public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, Long endTime = System.currentTimemillis () + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); }} system.out. println("---- time-consuming task executed --"); return START_STICKY; }}
Running the code above starts MyIntentService using a separate worker thread and therefore does not block the foreground UI thread; And MyService can.
Copyright notice: This article is the blogger’s original article, shall not be reproduced without the permission of the blogger.