Simple Use of Service

life cycle

context.startService() ->onCreate()- >onStartCommand()->Service running--call context.stopService() ->onDestroy() 

context.bindService()->onCreate()->onBind()->Service running--call>onUnbind() -> onDestroy() 

Basic knowledge

Services are generally divided into two types:

  1. Local Service is used within the application. In Service, you can call Context.startService() to start and Context.stopService() to end. Internally, you can call Service.stopSelf() or Service.stopSelfResult() to stop by yourself. No matter how many times startService() is invoked, it only needs to call stopService() once to stop.

  2. Remote Service is used between applications within the android system. Interfaces can be defined and exposed for other applications to operate on. The client establishes a connection to the service object and invokes the service through that connection. Call the Context.bindService() method to establish the connection and start to call Context.unbindService() to close the connection. Multiple clients can be bound to the same service. If the service is not loaded at this time, bindService() loads it first. It can be reused by other applications, such as defining a weather forecast service and providing calls to other applications.

Matters needing attention

The process of the same service, multiple start-ups and actual execution of the service:

When the service is first started, run onCreate -> onStartCommand

Later, when the service is started, the service only executes onStartCommand

In the actual use process, data is transferred through Intent and executed in OnStartCommand.

Types of services

According to the scope of use:

1. Local Service: Used within an application

Functions: Used to implement some time-consuming tasks of the application itself, such as querying upgrade information, not occupying the thread of the application such as Activity, but executing in the background of a single thread, so that the user experience is better.

Use: In Service, you can call Context.startService() to start and Context.stopService() to end. Internally, you can call Service.stopSelf() or Service.stopSelfResult() to stop by yourself. No matter how many times startService() is invoked, it only needs to call stopService() once to stop.

2. Remote Sercie: Used between applications within an android system

Function: It can be reused by other applications, such as weather forecast service. Other applications do not need to write such services any more, but can call existing ones.

Use: Interfaces can be defined and exposed for other applications to operate on. The client establishes a connection to the service object and invokes the service through that connection. Call the Context.bindService() method to establish the connection and start to call Context.unbindService() to close the connection. Multiple clients can be bound to the same service. If the service is not loaded at this time, bindService() loads it first.

Classified according to operation category:

1. Front Desk Service

The front-end service needs to call either startForeground (android 2.0 and later) or setForeground (before Android 2.0) to make the service a front-end service.
The use of foreground services can avoid the service being run in the background by the system KILL.

Use: As you can see, we only need to call the startForeground method in onStartCommand to make the service front-end run, and then call stopForeground in onDestroy to remove the front-end run.
So, for example, the music player in the mobile phone, whether the mobile phone is dormant or not, as long as it starts playing, the system will not go to the KILL service, only when the music is stopped playing, the service may be recycled and cleaned up.

2. Backstage services

Background service is running in the background.

Note: In local services, onStart has been replaced by onStartCommand method. Service and Active are derived from Context class. Context objects can be obtained by getApplicationContext() method. Like Active, onStart has its own life cycle, but it performs a slightly different process than Active. As shown in the figure above.

In the service classification, three types of service communication are mentioned, one is to start the service directly through startService(), the other is to start the service through bindService(), and the corresponding life cycle of the two modes is shown in the figure above. 3. Service using AIDL( AIDL parsing (1) An example of communication between two applications using AIDL,AIDL parsing (2) Let Service actively call up Activity!)

Simple use, two different ways of transmitting messages using broadcast and interface

Open Services

Out of Service

Binding services

Unbundling service

Exchange of messages

ServiceActivity

package com.bourne.android_common.ServiceDemo;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;

import com.bourne.android_common.R;
import com.bourne.common_library.utils.Logout;

public class ServiceActivity extends AppCompatActivity {

    MyConn conn;
    Intent intent;
    MyService.IService iService;
    MyService myService;
    private LocalBroadcastManager mLocalBroadcastManager;
    private MyBroadcastReceiver mBroadcastReceiver;
    public final static String ACTION_TYPE_MYSERVICE= "action.type.myservice";

    private int progress = 0;
    private ProgressBar mProgressBar;

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

        //Registered Broadcasting
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_TYPE_MYSERVICE);
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    }

    /**
     * Start up service
     *
     * @param view
     */
    public void start(View view) {
        intent = new Intent(ServiceActivity.this, MyService.class);
        startService(intent);
    }

    /**
     * Out of Service
     */
    public void stop(View view) {
        stopService(intent);
    }

    /**
     * Binding services
     */
    public void bind(View view) {
        conn = new MyConn();
        intent = new Intent(ServiceActivity.this, MyService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    /**
     * Binding services
     */
    public void unbind(View view) {
        unbindService(conn);
    }

    /**
     * Sending messages by broadcast
     */
    public void brocast(View view) {
        iService.callMethodInService();
    }

    /**
     * Connect Service
     */
    private class MyConn implements ServiceConnection {

            //Use broadcasting
            iService = (MyService.IService) service;

            //Using interface mode
            myService =  ((MyService.MyBinder)service).getService();
            //Register callback interface to receive changes in download progress
            myService.setOnProgressListener(new MyService.OnProgressListener() {

                @Override
                public void onProgress(int progress) {
                    mProgressBar.setProgress(progress);

                }
            });
        }

        public void onServiceDisconnected(ComponentName name) {

        }

    }

    /**
     * Receiving Sercice messages by broadcast
     */
    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {

                case ACTION_TYPE_MYSERVICE:
                    Logout.e("Activity Received from Service News");
                    break;
            }
        }
    }


    /**
     * Sending Messages by Interface
     */
    public void listener(View view) {
        //Start downloading
        myService.startDownLoad();
    }
}

MyService

package com.bourne.android_common.ServiceDemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;

import com.bourne.common_library.utils.Logout;

public class MyService extends Service {

    public interface IService {
        void callMethodInService();
    }

    public class MyBinder extends Binder implements IService {

        public void callMethodInService() {
            helloInservice();
        }

        /**
         * Get an instance of the current Service
         * @return
         */
        public MyService getService(){
            return MyService.this;
        }
    }

    /**
     * Radio broadcast
     */
    private LocalBroadcastManager mLocalBroadcastManager;

    /**
     * send message
     */
    private void sendBroadcast() {
        Intent intent = new Intent(ServiceActivity.ACTION_TYPE_MYSERVICE);
        mLocalBroadcastManager.sendBroadcast(intent);
    }

    public void helloInservice() {
        Logout.e("service Received from activity News");
        sendBroadcast();
    }

    public MyService() {
        Logout.e("MyService");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Logout.e("onStart");
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logout.e("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Logout.e("onCreate");
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        Logout.e("onDestroy");
        super.onDestroy();

    }

    @Override
    public IBinder onBind(Intent intent) {
        Logout.e("onBind");
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Logout.e("onUnbind");
        return super.onUnbind(intent);
    }

    public interface OnProgressListener {
        void onProgress(int progress);
    }
    /**
     * Maximum of progress bar
     */
    public static final int MAX_PROGRESS = 100;

    /**
     * Progress bar progress value
     */
    private int progress = 0;

    /**
     * Callback interface for updating schedule
     */
    private OnProgressListener onProgressListener;


    /**
     * Register callback interface methods for external callbacks
     * @param onProgressListener
     */
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

    /**
     * Add get() method for Activity call
     * @return Download progress
     */
    public int getProgress() {
        return progress;
    }

    /**
     * Simulated download task, updated every second
     */
    public void startDownLoad(){
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(progress < MAX_PROGRESS){
                    progress += 5;

                    //Notify caller of progress change
                    if(onProgressListener != null){
                        onProgressListener.onProgress(progress);
                    }

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

                }
            }
        }).start();
    }


}

AndroidManifest

     <service android:name=".ServiceDemo.MyService"></service>

Reference resources

Keywords: Android Mobile

Added by savedlema on Sun, 07 Jul 2019 05:41:50 +0300