Android Service Summary

Reference link: http://www.cnblogs.com/lwbqqyumidi/p/4181185.html

  Service is often encountered on Android, and the ones used are relatively scattered. Today, I have a more comprehensive understanding.

  Service is also one of the components. If you want to use it, you need to register it in the manifest file. The code is as follows:
  <service
    android:exported=["true" | "false"]
    android:icon="drawable resource"
    android:name="string"
    android:process="string" >
    . . .
  </service> The
  above is Several attributes are used, name is the service class, and process is the process name. Whether exported allows remote calls.

The following is a simple implementation of the service class:
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.
import android.util.Log;


public class MyService extends Service {

    public static final int MSG_SEND_TO_SERVER = 1;
    public static final int MSG_SEND_TO_CLIENT = 2;

    private Messenger mClientMessenger;
    private Messenger mServerMessenger = new Messenger(new ServerHandler());

    private static int mark =1;

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

    class ServerHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SEND_TO_SERVER:
                    mClientMessenger = msg.replyTo;
                    Message toClientMsg = Message.obtain(null, MSG_SEND_TO_CLIENT);
                    toClientMsg.obj = "来自Service:" + mark;
                    try {
                        mClientMessenger.send(toClientMsg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    mark++;
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

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

    @Override
    public void onDestroy() {
        Log.e("123","onDestroy");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
}

Activity调用service简单代码如下:
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tvRecord;
    private Button btnBindService;
    private Button btnStartService;
    private Button btnSend;
    private Button btnUnBindService;
    private Button btnStopService;

    private ServiceConnection sc = new MyServiceConnnect();
    private boolean isConnnect =false;


    private Messenger mServerMessenger;
    private Handler mClientHandler = new MyClientHandler();
    private Messenger mClientMessenger = new Messenger(mClientHandler);

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

        findView();
        setListener();
    }

    private void setListener(){
        btnBindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                bindService(intent, sc, Context.BIND_AUTO_CREATE);
            }
        });
        btnStartService.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });
        btnSend.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                send();
            }
        });
        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                stopService(intent);
            }
        });
        btnUnBindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isConnnect) {
                    unbindService(sc);
                    isConnnect = false;
                }
            }
        });
    }

    private void send(){
        if (!isConnnect){
            return;
        }
        Message msg = Message.obtain(null, MyService.MSG_SEND_TO_SERVER);
        msg.replyTo = mClientMessenger;
        try {
            mServerMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void findView(){
        tvRecord = (TextView)findViewById(R.id.tv_record);
        btnBindService = (Button) findViewById(R.id.btn_bind);
        btnStartService = (Button)findViewById(R.id.btn_start);
        btnSend = (Button)findViewById(R.id.btn_send);
        btnStopService = (Button)findViewById(R.id.btn_stop);
        btnUnBindService = (Button)findViewById(R.id.btn_unbind);
    }

    class MyClientHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MyService.MSG_SEND_TO_CLIENT) {
                String obj = (String)msg.obj;
                tvRecord.setText(obj);
            }
        }
    }

    class MyServiceConnnect implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mServerMessenger = new Messenger(service);
            isConnnect =true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isConnnect =false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}


  Generally, there are two methods to start a service: startService and bindService.
  startService is relatively simple and ends through stopService. When the service has been started, the oncreate method will not be called, and onStartCommand will be called directly. The meaning of the return value of startCommand is as follows:
START_NOT_STICKY: When the Service is killed by the system due to insufficient memory, the system will not try to recreate the Service even if the system memory is available enough in the future. Unless the Client explicitly calls startService(...) again in the program to start the Service.

START_STICKY: After the Service is killed by the system due to insufficient memory, the system will try to recreate the Service at a certain time in the future when the system memory is sufficient. Once the creation is successful, it will call back onStartCommand(.. .) method, but the Intent in it will be null, except for the pendingintent.

START_REDELIVER_INTENT: The only difference from START_STICKY is that when the onStartCommand(...) method is called back, the intent in it will be non-null and will be the intent in the last call to startService(...).

START_STICKY_COMPATIBILITY: compatibility version of {@link #START_STICKY} that does not guarantee that {@link #onStartCommand} will be called again after being killed. This value is generally not used, so pay attention to the first three situations.

  bindService can also start a service, and can end it through unbindService, which can communicate through the interface and through the messenger. The specific code is as above. If a service is started through bindservice, all dependencies must be closed before the service can be terminated.

Guess you like

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