1 Reception Service

Because the service has a low priority, when the system is out of memory, services running in the background may be reclaimed. If you want to avoid a service being reclaimed, you can use a foreground service.

The foreground service will always have an icon displayed in the status bar of the system. If you pull down the status bar, you can see more detailed information, similar to the effect of message notification.

public class FirstService extends Service {

    private static final String TAG = "FirstService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate"); Intent Intent = new Intent(this, mainactivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); Notification notification = new NotificationCompat.Builder(this) .setContentTitle("Can Messi beat France in the biggest embarrassment of his career?")
                .setContentText("1/8 of the World Cup final, the French against Argentina, France coach didier deschamps will usher in 80 milestone, become a team coach, most coaching session record Gaul rooster can keep the past 40 years in the World Cup in South American team's unbeaten golden body, Gerry boltzmann can find best, messi will break the previous World Cup knockout goal drought in the 666th minute, Are the key points of this battle.") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) .setContentIntent(pendingIntent) .build(); startForeground(1,notification); }}Copy the code

After you build the Notification object here, call startForeground() to make the current service a foreground service.

StartForeground receives two parameters:

parameter instructions
id Inform the ID
Notification Notification object

Effect:

2 IntentService

If time-consuming operations are handled in a service, ANR (Application Not Responding) problems tend to occur.

To avoid the possibility of starting a child thread in a specific method of the main service and then performing time-consuming operations in the child thread, such as:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
	Log.d(TAG, "onStartCommand"); // Perform time-consuming operations on child threads new Thread(new)Runnable() {
		@Override
		public void run() {// Time-consuming operation}}).start();return super.onStartCommand(intent, flags, startId);
}
Copy the code

Such a service, once started, runs until stopService() or stopSelf() is called. We can call stopSelf() to stop the service after the time-consuming operation is completed:

new Thread(new Runnable() {
	@Override
	public void run() {// stopSelf(); } }).start();Copy the code

Android provides the IntentService class to create an asynchronous, self-executing service.

Let’s create a new class that inherits from IntentService:

public class SecondService extends IntentService {
    private static final String TAG = "SecondService";

    public SecondService() {
        super("SecondService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "Child thread ID (Intent service) :"+ Thread.currentThread().getId()); } @override public voidonDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy"); }}Copy the code

** Note: ** This class must provide a no-argument constructor, and the parent class’s argument constructor must be called inside the constructor.

Next, launch the Intent service in the activity class:

Log.d(TAG, "Main thread ID:" + Thread.currentThread().getId());
Intent intentService = new Intent(context, SecondService.class);
startService(intentService);
Copy the code

Output result:

D/MainActivity: main thread ID: 1 D/SecondService: child thread ID (Intent service) : 145 D/SecondService: onDestroy

As you can see from the results, the IntentService service class starts a new thread to execute the time-consuming logic and stops automatically when the execution is complete. Isn’t it very convenient