IntentService of Service of Android's four major components

1. The meaning of IntentService

        Asynchronous, automatically stopped service.

Two, the difference between IntentService and service

        The service service runs in the main thread by default. If you process some time-consuming logic directly in the service, ANR may occur, so we generally open a new thread in the specific method of the service to process the specific logic. Then, once this type of service is started, it will run all the time. To stop the service, you have to call stopSeft()

Then Android specifically provides IntentService to simply create asynchronous, automatically stopped services.

Three, the use of IntentService

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("name");
        Log.d("Kathy", "Constructor");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("Kathy", "onCreate()" + " ,Thread Name = " + Thread.currentThread().getName());
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d("Kathy", intent.getStringExtra("data") + " ,Thread Name = " + Thread.currentThread().getName());

        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("Kathy", "onDestroy()");
    }
}

public class IntentServiceDemoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service_demo);

        Intent intent = new Intent(this,MyIntentService.class);
        intent.putExtra("data","Kathy");
        startService(intent);
    }
}

result:

 Result analysis: You can see that asynchronous time-consuming operations are performed in onHandleIntent, and the service is automatically stopped.

4. Principle analysis

 When a task comes in, onStartCommand()-->onStart() will be sent, and a message will be sent to the handler to bring the task information. In the handleMessage of the handler, we will use our rewritten onHandleIntent() to process the task. After executing onHandleIntent(), it will stopSelf(msg.arg1).

Guess you like

Origin blog.csdn.net/sunbinkang/article/details/121282091