Communication between Service and IntentService, Service and Activity

Service

/**
         * One of the four major components of Android, Service is an application component that runs long-term in the background.
         * Service is not a process, nor a thread, it is in the same process as the application
         * Service can not do time-consuming operations, running in the main thread.
         */

@ServiceApplication Scenario

Play music in the background, locate the service, and interact with the server at regular intervals. Wait.

serviceTwo startup methods, and life cycle

这里写图片描述

/**
         * > startService:
         * Service is started multiple times in the system, onCreate will only be executed once, and the onStartCommand method is called the same number of times as the number of starts.
         *
         * > stopService
         * After calling stopService, the onDestroy method will be executed internally. If a Service is bound, calling stopService is invalid if there is no unbinding.
         *
         * > bindService
         * Bind Service internally calls onCreate, onBind
         *
         * > unBindService
         * Unbind Service, internal call onUnbind, onDestroy
         */

special case, combination of startup service and binding service

/**
         * > Use scene
         *
         * Use startService to start a background service. When you need to get the background information, you can bind the activity to the service. If you don't need it, you need to unbind it first.
         *
         * > The startup service has a higher priority than the binding service
         *
         * Bind the service after starting the service, the life cycle remains unchanged
         * Start the service after binding the service, and the life cycle becomes the startup service.
         */

Service and Activity communication (important)

/**
         * Activity passes data to Service using Intent
         * Service uses the Binder mechanism to pass data to the Activity, which is not very easy to use (EventBus is recommended here)
         *
         * About EventBus Video Tutorial
         * https://ke.qq.com/course/171663#term_id=100200824
         */

IntentService (recommended)

/**
         * IntentService is a class that inherits from Service and handles asynchronous requests.
         * There is a worker thread inside the IntentService to handle time-consuming operations.
         * The way to start the IntentService is the same as starting a traditional Service.
         * At the same time, when the task is executed, the IntentService will automatically stop without us having to manually control it.
         * In addition, you can start the IntentService multiple times.
         * Each time-consuming operation is executed in the IntentService's onHandleIntent callback method in the form of a work queue.
         * Also, only one worker thread will be executed at a time, the second one will be executed after the first one, and so on.
         *
         * Moreover, all requests are in a single thread and do not block the application's main thread (UI Thread).
         * Only one request is processed at a time. So, what are the benefits of using IntentService?
         * First of all, we have saved the trouble of manually opening threads in the Service.
         * Second, we don't have to manually stop the service when the operation is complete.
         */

一Demo (need to be registered in Manifest)

这里写图片描述

	<application
       ...
        <service android:name=".Service.MyIntentService"/>
    </application>
import android.content.Intent;
Import android.os.Bundle;
Import android.support.v7.app.AppCompatActivity;
Import android.view.View;
Import android.widget.Button;
Import android.widget.TextView;

Import com.example.zhangyu.myintentservice.Bean.UpdateMain;
Import com.example.zhangyu.myintentservice.Service.MyIntentService;

Import org.greenrobot.eventbus.EventBus;
Import org.greenrobot.eventbus.Subscribe;
Import org.greenrobot.eventbus.ThreadMode;

Public class MainActivity extends AppCompatActivity {

    Private button button;
    Private TextView textView;

    @Override
    Protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    Public void EventBusReceiver(UpdateMain updateMain) {
        textView.setText(updateMain.getI() + "");
    }

    Private void initView() {
        Button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            Public void onClick(View v) {
                / / Best to use getApplicationContext
                Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
                intent.putExtra("url", "https://www.baidu.com/");
                startService(intent);
            }
        });
    }

    @Override
    Protected void onDestroy() {
        super.onDestroy();
        If (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
Import android.app.IntentService;
Import android.content.Intent;
Import android.support.annotation.Nullable;
Import android.util.Log;
Import com.example.zhangyu.myintentservice.Bean.UpdateMain;

Import org.greenrobot.eventbus.EventBus;

Public class MyIntentService extends IntentService {
    Private final String TAG = "MyIntentService";

    /**
     * Creates an IntentService. Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    Public MyIntentService(String name) {
        Super(name);
    }

    Public MyIntentService() {
        This("MyIntentServiceThread");
    }


    @Override
    Protected void onHandleIntent(@Nullable Intent intent) {
        String url = intent.getStringExtra("url");
        Log.d(TAG, "onHandleIntent: " + url);
        / / Simulate time-consuming operations, pay attention to not need to open child threads
        For (int i = 0; i < 5; i++) {
            Try {
                Thread.sleep(1000);
                UpdateMain updateMain = new UpdateMain();
                updateMain.setI(i);
                EventBus.getDefault().post(updateMain);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Log.d(TAG, "onHandleIntent: " + Thread.currentThread().getName());
    }

    @Override
    Public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }


}