Strongly Recommend Articles: Welcome to Collection
Android Dry Goods Sharing
Read for five minutes, ten o'clock a day, and study with you for life. Here's Android, a programmer.
This article mainly introduces some knowledge points in Android development. By reading this article, you will gain the following contents:
- Introduction to Service
- One of the four components must be registered in Androidmainfest.xml
- Startup mode startup service
- Binding Mode Binding Service
- Front Office Service
- AIDL Remote Service
Service is one of the four components of Android (Activity Activity, Service Service Service, Content Provider Content Provider, Broadcast Receiver Broadcasting). Compared with Activity, Activity runs in the foreground, users can see, Service runs in the background, without user interface, users can not see.
Service is mainly used for interaction between components (e.g. interaction with Activity, ContentProvider, Broadcast Receiver), time-consuming background operations (e.g. downloading files, playing music, etc.), but service can not run longer than 20 seconds in the main thread, otherwise ANR will appear. Time-consuming operations are generally recommended in sub-threads. Operate.
1. Introduction to Service
Before we understand the life cycle of Service, let's first understand the inheritance relationship of Service, so that we can better understand Service.
Service inheritance is as follows:
java.lang.Object ↳ android.content.Context ↳ android.content.ContextWrapper ↳ android.app.Service
Two Startup Modes of Service
Service has two different startup modes, and different startup modes correspond to different life cycles.
Service startup mode is divided into two main types: 1. Startup mode. 2. Binding mode.
1. Startup mode
This mode is started by the startService() method, which can run in the background all the time and will not die with the death of the startup component. It can only perform a single operation, and can not return the result to the caller. It is often used for downloading, uploading files, playing music and so on.
2. Binding mode
This pattern is initiated by calling bindService() from a binding component (Activity, etc.), which is unbounded with the death of the binding component.
If no other startService() is started at this time, the service will die with the death of the binding component.
Multiple components can not only bind a Service at the same time, but also perform cross-process operations through interprocess communication (IPC).
3. Two services can run simultaneously
The Service in startup mode and binding mode can run at the same time. When the Service is destroyed, the Service can only be destroyed if both modes do not use Service, otherwise it will cause an exception.
4. Life Cycle of Two Service Patterns
The life cycles of the two Service modes are as follows:
2. One of the four components must be registered in Androidmainfest.xml
Service registration method is as follows:
<manifest ... > ... <application ... > <service android:name=".ServiceMethods" /> ... </application> </manifest>
Be careful:
If service is not registered, it will not cause App Crash like Activity. Service will not report abnormal information without registering, but the service will not come up, and it is easy to be confused if it does not pay attention to it.
3. Startup mode
Service started by boot mode, if not actively shut down, the service will always be.
How to Start Services in Startup Mode
Intent mBindIntent = new Intent(ServiceMethods.this, BindServiceMethods.class); startService(mStartIntent);
Start Mode Starts the Life Cycle of Services
Here is a way to validate the lifecycle of service startup in startup mode. For a detailed lifecycle, see the lifecycle diagram of Service above.
01-03 17:16:36.147 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onCreate---- 01-03 17:16:36.223 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onStartCommand---- 01-03 17:16:38.174 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onDestroy----
Startup mode startup service case
This case function: Start the service and create notifications in the service
// Service Creation Method @Override public void onCreate() { super.onCreate(); Log.i(TAG, "----onCreate----"); } // Service Startup Method @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "----onStartCommand----"); // Get Notification Manager instance notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Instantiate NotificationCompat.Builder and set related properties NotificationCompat.Builder builder = new NotificationCompat.Builder( this) // Setting small icons .setSmallIcon(R.drawable.ic_launcher) .setLargeIcon( BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) // Setting Notification Title .setContentTitle("I passed StartService Notification of service startup") // Setting notification cannot be automatically cancelled .setAutoCancel(false).setOngoing(true) // Set the notification time, default to the time when the system notifies, usually not set // .setWhen(System.currentTimeMillis()) // Setting Notification Content .setContentText("Please use StopService Method Stop Service"); // Generate Notification object through builder.build() method and send notification, id=1 notifyManager.notify(1, builder.build()); return super.onStartCommand(intent, flags, startId); } // Service Destruction Method @Override public void onDestroy() { Log.i(TAG, "----onDestroy----"); notifyManager.cancelAll(); super.onDestroy(); }
4. Binding Mode Starts Binding Service
The Service started in binding mode will be unbound as the binding gradually disappears. If the Service is not started in startup mode at this time, the Service will be destroyed.
The Method of Starting Binding Service in Binding Mode
Binding mode is a Service that is started through other components.
How to Start Binding Mode Service
// Start Binding Service Processing Method public void BtnStartBindService(View view) { // Start Binding Service Processing Method bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE); isBindService = true; Toast.makeText(ServiceMethod.this, "start-up " + mBindCount + " Sub-Binding Service", Toast.LENGTH_SHORT).show(); } public void BtnSopBindService(View view) { if (isBindService) { // Unbound Service Processing Method unbindService(serviceConnection); Toast.makeText(ServiceMethod.this, "Relieve " + mUnBindCount + " Sub-Binding Service", Toast.LENGTH_SHORT).show(); isBindService = false; } }
Binding services die with the death of binding components
The lifecycle callback code for the binding pattern is as follows:
// Service Creation Method @Override public void onCreate() { super.onCreate(); Log.i(TAG, "----onCreate----"); } // Service binding method @Override public IBinder onBind(Intent intent) { Log.i(TAG, "----onBind----"); MyBinder myBinder = new MyBinder(); return myBinder; } // Service unbinding method @Override public boolean onUnbind(Intent intent) { Log.i(TAG, "----onUnbind----"); return super.onUnbind(intent); } // Service Destruction Method @Override public void onDestroy() { Log.i(TAG, "----onDestroy----"); super.onDestroy(); }
The life cycle code of the binding service prints the Log information as follows:
01-03 20:32:59.422 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onCreate---- 01-03 20:32:59.423 13306-13306/com.android.program.programandroid I/BindService wjwj:: -----onBind----- 01-03 20:33:09.265 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onUnbind---- 01-03 20:33:09.266 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onDestroy----
Binding service case
Function: Get the number of times the binding mode starts the binding service and unbounds the service
Binding service classes
package com.android.program.programandroid.component.Service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class BindServiceMethods extends Service { private static final String TAG = "BindService wjwj:"; public BindServiceMethods() { } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "----onCreate----"); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "----onBind----"); MyBinder myBinder = new MyBinder(); return myBinder; } @Override public boolean onUnbind(Intent intent) { Log.i(TAG, "----onUnbind----"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.i(TAG, "----onDestroy----"); super.onDestroy(); } }
- Interaction between components and binding service classes
// Start Binding Service Processing Method public void BtnStartBindService(View view) { bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE); isBindService = true; Toast.makeText(ServiceMethods.this,"start-up "+mBindCount+" Sub-Binding Service",Toast.LENGTH_SHORT).show(); } // Unbound Service Processing Method public void BtnSopBindService(View view) { if (isBindService) { unbindService(serviceConnection); Toast.makeText(ServiceMethods.this,"Relieve "+mUnBindCount+" Sub-Binding Service",Toast.LENGTH_SHORT).show(); isBindService=false; } }
- Binder interface class required for interaction between components
/** * This class provides the interface between the binding component and the binding service provider * */ public class MyBinder extends Binder { private int count = 0; public int getBindCount() { return ++count; } public int getUnBindCount() { return count> 0 ? count-- : 0; } }
5. Improving the Priority of Services
The default way to start a service is backstage service, but by setting the service as the front service, the priority of the service can be increased, thus avoiding the service process being killed when the memory of the mobile phone is tight.
Two Methods of Setting up Front Office Service
1. Set up as Front Desk Service
//Set up as Front Desk Service startForeground(int, Notification)
2. Cancellation of Front Desk Service
//Cancel Front Desk Service stopForeground(true);
Start Foreground Front Office Service Case
Function: Front-end service binding notification information, improve the priority of service process, otherwise cancel notification information
package com.android.program.programandroid.component.Service; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import com.android.program.programandroid.R; public class MyStartForcegroundService extends Service { public MyStartForcegroundService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getAction().equals("start_forceground_service")) { // Get Notification Manager instance NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Instantiate NotificationCompat.Builder and set related properties NotificationCompat.Builder builder = new NotificationCompat.Builder(this) // Setting small icons .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) // Setting Notification Title .setContentTitle("I passed startForeground Start the Front Desk Service Notice") // Setting notification cannot be automatically cancelled .setAutoCancel(false) .setOngoing(true) // Set the notification time, default to the time when the system notifies, usually not set // .setWhen(System.currentTimeMillis()) // Setting Notification Content .setContentText("Please use stopForeground Method Changed to Backstage Service"); //Generate Notification object through builder.build() method and send notification, id=1 // Set up as Front Desk Service startForeground(1, builder.build()); } else if (intent.getAction().equals("stop_forceground_service")) { stopForeground(true); } return super.onStartCommand(intent, flags, startId); } }
6. Using AIDL Interface to Realize Remote Binding
As there are many contents, a detailed introduction will be given in the following section.
So far, this article is over. If there are any mistakes, you are welcome to make suggestions and corrections. At the same time look forward to your attention, thank you for reading, thank you!