Use of Android basic IntentService

Use of Android basic IntentService

A brief description of the service

1. Foreground service and IntentService:

The foreground service can keep running all the time without being recycled due to insufficient system memory.

Service service test preparation code

We use a specific case to illustrate the introduction of the service life cycle of the start and bind methods. The project results are as follows:

1. Do some initialization work in MainActivity.java , as follows:

  1. private   final   static String TAG = "MyIntentService" ;
  2. private MyIntentService.MyBinder binder;
  3.  
  4. private ServiceConnection connection = new ServiceConnection() {
  5. @Override
  6.      public   void onServiceConnected(ComponentName name, IBinder service) {
  7. binder = (MyIntentService.MyBinder) service;
  8. binder.sayHello(name.getClassName());
  9. }
  10.  
  11. @Override
  12.      public   void onServiceDisconnected(ComponentName name) {
  13. Log.i(TAG, "service disconnect: " + name.getClassName());
  14. }
  15. };
  16.  
  17. @Override
  18. protected   void onCreate(Bundle savedInstanceState) {
  19.      super .onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. }

2. Create a simple IntentService service class : MyIntentService

  1. package com.example.linux.intentservicetest;
  2.  
  3. import android.app.IntentService;
  4. import android.content.Intent;
  5. import android.os.Binder;
  6. import android.os.IBinder;
  7. import android.util.Log;
  8.  
  9. public   class MyIntentService extends IntentService {
  10.      private   final   static String TAG = "MyIntentService" ;
  11.      private MyBinder myBinder = new MyBinder();
  12.  
  13.      class MyBinder extends Binder {
  14.          public   void sayHello(String name) {
  15. Log.i(TAG, "say hello method: " + name);
  16. }
  17.  
  18.          public   void sayWorld(String name) {
  19. Log.i(TAG, "say world method: " + name);
  20. }
  21. }
  22.  
  23. @Override
  24.      public IBinder onBind(Intent intent) {
  25.          return myBinder;
  26. }
  27.  
  28.      public MyIntentService() {
  29.          super ( "MyIntentService" );
  30. Log.i(TAG, "myintent service constructor." );
  31. }
  32.  
  33. @Override
  34.      public   void onCreate() {
  35. Log.i(TAG, "on create." );
  36.          super .onCreate();
  37. }
  38.  
  39. @Override
  40.      protected   void onHandleIntent(Intent intent) {
  41. Log.i(TAG, "handle intent: " + intent.getStringExtra( "username" ) + ", thread: " + Thread.currentThread());
  42. }
  43.  
  44. @Override
  45.      public   void onDestroy() {
  46.          super .onDestroy();
  47. Log.i(TAG, "on destroy." );
  48. }
  49.  
  50. @Override
  51.      public   int onStartCommand(Intent intent, int flags, int startId) {
  52. Log.i(TAG, "on start command." );
  53.          return   super .onStartCommand(intent, flags, startId);
  54. }
  55.  
  56. @Override
  57.      public   boolean onUnbind(Intent intent) {
  58.          //Default return false  
  59. String username = intent.getStringExtra( "username" );
  60. Log.i(TAG, "on unbind: " + super .onUnbind(intent) + ", username: " + username);
  61.          return   true ;
  62. }
  63.  
  64. @Override
  65.      public   void onRebind(Intent intent) {
  66. Log.i(TAG, "on rebind" );
  67.          super .onRebind(intent);
  68. }
  69. }

3. Create a simple front desk service class : FrontService

  1. package com.example.linux.intentservicetest;
  2.  
  3. import android.app.Notification;
  4. import android.app.PendingIntent;
  5. import android.app.Service;
  6. import android.content.Intent;
  7. import android.os.IBinder;
  8. import android.util.Log;
  9.  
  10. public   class FrontService extends Service {
  11.      private   final   static String TAG = "MyIntentService" ;
  12.      public FrontService() {
  13. Log.i(TAG, "front service constructor" );
  14. }
  15.  
  16. @Override
  17.      public IBinder onBind(Intent intent) {
  18.          return   null ;
  19. }
  20.  
  21. @Override
  22.      public   void onCreate() {
  23.          super .onCreate();
  24. Notification.Builder builder = new Notification.Builder( this );
  25. Intent intent = new Intent( this , MainActivity. class );
  26. PendingIntent pendingIntent = PendingIntent.getActivity( this , 0, intent,
  27. PendingIntent.FLAG_CANCEL_CURRENT);
  28.  
  29. builder.setSmallIcon(R.mipmap.ic_launcher).setTicker( "ticker" );
  30. builder.setWhen(System.currentTimeMillis()).setAutoCancel( true );
  31. builder.setContentTitle( "content title" ).setContentText( "content text" );
  32. builder.setContentIntent(pendingIntent);
  33.  
  34. Notification notify = builder.getNotification();
  35.  
  36. notify.defaults = Notification.DEFAULT_ALL;
  37. startForeground(10, notify);
  38. }
  39. }

4. Register services and activities in AndroidManifest.xml :

  1. <activity android:name= ".MainActivity" >
  2. <intent-filter>
  3. <action android:name= "android.intent.action.MAIN" />
  4. <category android:name= "android.intent.category.LAUNCHER" />
  5. </intent-filter>
  6. </activity>
  7.  
  8. <service
  9. android:name= ".MyIntentService"  
  10. android:exported= "false" >
  11. </service>
  12. <service
  13. android:name= ".FrontService"  
  14. android:enabled= "true"  
  15. android:exported= "true" >
  16. </service>

Use of Intent Service

1. Create methods in MainActivity to start and stop services:

  1. // Start the service  
  2. public   void startService(View view) {
  3. Intent intent = new Intent();
  4. intent.putExtra( "username" , "linux" );
  5. intent.setClass(MainActivity. this , MyIntentService. class );
  6. startService(intent);
  7. }
  8.  
  9. // Stop the service  
  10. public   void stopService(View view) {
  11. Intent intent = new Intent();
  12. intent.setClass(MainActivity. this , MyIntentService. class );
  13. stopService(intent);
  14. }

2. Create a method in MainActivity to bind and unbind services:

  1. // Bind service  
  2. public   void bindService(View view) {
  3. Intent intent = new Intent();
  4. intent.setClass(MainActivity. this , MyIntentService. class );
  5. intent.putExtra( "username" , "linux" );
  6.      boolean isBind = bindService(intent, connection, Context.BIND_AUTO_CREATE);
  7. Log.i(TAG, "bind service: " + isBind);
  8. }
  9.  
  10. // Unbind service  
  11. public   void unbindService(View view) {
  12. Intent intent = new Intent();
  13. intent.setClass(MainActivity. this , MyIntentService. class );
  14. unbindService(connection);
  15. }

3. Operation results :

Click start:

  1. 03-25 08:01:53.460 8389-8389/? I/MyIntentService: myintent service constructor.
  2. 03-25 08:01:53.460 8389-8389/? I/MyIntentService: on create.
  3. 03-25 08:01:53.475 8389-8389/? I/MyIntentService: on start command.
  4. 03-25 08:01:53.477 8389-8727/? I/MyIntentService: handle intent: linux, thread: Thread[IntentService[MyIntentService],5,main]
  5. 03-25 08:01:53.478 8389-8389/? I/MyIntentService: on destroy.


Click stop: no output Click bind:

  1. 03-25 08:02:25.421 8389-8389/? I/MyIntentService: bind service: true  
  2. 03-25 08:02:25.422 8389-8389/? I/MyIntentService: myintent service constructor.
  3. 03-25 08:02:25.422 8389-8389/? I/MyIntentService: on create.
  4. 03-25 08:02:25.432 8389-8389/? I/MyIntentService: say hello method: com.example.linux.intentservicetest.MyIntentService

Click unbind:

  1. 03-25 08:02:28.486 8389-8389/? I/MyIntentService: on unbind: false , username: linux
  2. 03-25 08:02:28.490 8389-8389/? I/MyIntentService: on destroy.

Use of front desk services

1. Create a method in MainActivity to start the foreground service:

  1. //Use of foreground service  
  2. public   void frontService(View view) {
  3. Intent intent = new Intent();
  4. intent.setClass(MainActivity. this , FrontService. class );
  5. startService(intent);
  6. }

2. Operation results : In the notification bar of the mobile phone

Analysis of the principle of IntentService

1. intentService is an abstract method that inherits Service :

  1. public   abstract   class IntentService extends Service

2. Some fields contained in intentService are referenced as follows :

  1. private   volatile Looper mServiceLooper;
  2. private   volatile ServiceHandler mServiceHandler;
  3. private String mName;
  4. private   boolean mRedelivery;
  5.  
  6. private   final   class ServiceHandler extends Handler {
  7.      public ServiceHandler(Looper looper) {
  8.          super (looper);
  9. }
  10.  
  11. @Override
  12.      public   void handleMessage(Message msg) {
  13. onHandleIntent((Intent)msg.obj);
  14. stopSelf(msg.arg1);
  15. }
  16. }

2. When starting a service, the constructor is executed first, followed by the onCreate method, and then the onStartCommand method. The onStart method is executed in onStartCommand (the execution process is described in Android Basics ----> Service Lifecycle):

The onCreate method starts a thread, gets the Looper and initializes a Handler

  1. @Override
  2. public   void onCreate() {
  3.      // TODO: It would be nice to have an option to hold a partial wakelock  
  4.      // during processing, and to have a static startService(Context, Intent)  
  5.      // method that would launch the service & hand off a wakelock.  
  6.  
  7.      super .onCreate();
  8. HandlerThread thread = new HandlerThread( "IntentService[" + mName + "]" );
  9. thread.start();
  10.  
  11. mServiceLooper = thread.getLooper();
  12. mServiceHandler = new ServiceHandler(mServiceLooper);
  13. }

onStart method, using the above Handler to send information

  1. @Override
  2. public   void onStart(Intent intent, int startId) {
  3. Message msg = mServiceHandler.obtainMessage();
  4. msg.arg1 = startId;
  5. msg.obj = intent;
  6. mServiceHandler.sendMessage(msg);
  7. }

onStartCommand method, calls onStart method, sends information

  1. @Override
  2. public   int onStartCommand(Intent intent, int flags, int startId) {
  3. onStart(intent, startId);
  4.      return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
  5. }
  6.  


***The above Handler gets the information and calls the handleMessage method, which contains the stopSelf(msg.arg1) method to stop the service:

3. Here are two methods of the service class, the source code is android6.0

The onStart method in Service has been deprecated:

  1. /**
  2. * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.
  3. */  
  4. @Deprecated
  5. public   void onStart(Intent intent, int startId) {
  6. }

In the onStartCommand method

  1. public   int onStartCommand(Intent intent, int flags, int startId) {
  2. onStart(intent, startId);
  3.      return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
  4. }
  5.  

<<:  HTTP in iOS Just look at me

>>:  Teach you step by step how to quickly earn your first pot of gold in the VR industry

Recommend

Sharing of iOS network layer architecture design

[[166105]] Preface A few days ago, I helped the c...

APP operation indicators and promotion and marketing suggestions!

How to do a good job in App operation and promoti...

Write an iOS network request library by yourself - encapsulation interface

Code example: https://github.com/johnlui/Swift-On...

2014 TOP100 Open Source Software

I don't know when it started, but many people...

40 private domain tips from 0 to 1!

During this period, we have been providing privat...

WeChat 8.0.6 iOS version is officially launched with these 6 major changes

In actual testing, although there are no major fu...

iOS unit testing: translation - common ways to use OCMock

The API used in this article is the old version o...

How can a novice master Dreamweaver? How to build a Dreamweaver website?

How to play the Dreamweaver website for beginners...

Online Live Traffic Drainage Course Practical Manual

A high-conversion live class can bring hundreds o...

Mobile product operation: 9 factors affecting ASO optimization

An app with a good ranking in search engines can ...

Windows Phone's itch for domestic market share

Windows Phone (abbreviated as WP) is a mobile pho...