bind service

The local service (Local) does not need IPC or AIDL. After the main process is Killed, the service will be terminated.

The Remote Service is  an independent process, so when the process where the Activity is located is Killed, the service is still running and is not affected by other processes, and it is troublesome to use AIDL for IPC. Generally used for system Service, which is resident.

 

What is the use of binding Service?

Execute some functions in Service through Activity

 

 

Steps to bind the service:

1. Create a class, extends Service

2. Create a Binder object

3. Return the Binder object in the onBind() method

 

public class MyService extends Service {

    public MyService() {
    }

    private DownloadBinder mBinder = new DownloadBinder();

    class DownloadBinder extends Binder {

        public void startDownload() {
            Log.d("MyService", "startDownload executed");
        }

        public int getProgress() {
            Log.d("MyService", "getProgress executed");
            return 0;
        }

    }

    @Override
public IBinder onBind(Intent intent) {
        return mBinder;
    }
....

 

 

 

4. In the main thread, create a Connection object and call various methods through the downloadBinder object

 

private ServiceConnection connection = new ServiceConnection() {

    @Override
public void onServiceDisconnected(ComponentName name) {
    }

    @Override
public void onServiceConnected(ComponentName name, IBinder service) {
        downloadBinder = (MyService.DownloadBinder) service;
        downloadBinder.startDownload();
        downloadBinder.getProgress();
    }
};

 

 5. Add the code to start the service and bind the service to the main thread

Intent intent = new Intent(this, DownloadService.class);
startService(intent); // start service
 bindService(intent, connection , BIND_AUTO_CREATE ); // bind service

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326181202&siteId=291194637