Android Service启动方式总结

1、StartService()启动Service的方式:
    onCreate--> onStartCommand ( 可多次调用 )-->onDestroy
    在onCreate()后,每次startService()将会直接进入onStartCommand,onStart()已经被废弃
    在Activity中调用stopService()或在service内部调用stopSelf()结束Service

2、对于 bindService() 启动 Service 会经历:
     context.bindService()->onCreate()->onBind()->Service running-->onUnbind() -> onDestroy() ->Service stop
     Service是可以和多个Activity进行绑定的,但要注意的是,当Activity结束时一定要跟相应的Service解除绑定,不然是会报异常的(Main4Activity has leaked ServiceConnection),虽然此时即使报异常也不会影响Activity的结束了,然后还是会强制的解除绑定。
     当多个Activity与Service进行绑定的时候,只有当所有的绑定都解除了之后,Service才会结束。

3、对于既用StartService()和bindService()启动的Service:
   这种调用方法可以起到即使与Service绑定的Activity结束了,Service依然不会死掉。这种方式启动的Service需要同时调用stopService()和unbindService()解除了所有绑定之后才能结束Service。

下面是两个Activity绑定一个Service的演示代码:
第一个Activity:
package com.example.administrator.androidtrainingtest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class Main3Activity extends AppCompatActivity {


    private boolean flag;
    private static final String TAG = "TestActivity";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        Button btnStart = (Button) findViewById(R.id.btnStart);

        Button btnStop = (Button) findViewById(R.id.btuStop);

        Button butStartActivity = (Button) findViewById(R.id.btnStartActivity);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动service 方式2
                bindService();
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //停止service 方式2
                unBindService();
            }
        });

        butStartActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main3Activity.this, Main4Activity.class));
            }
        });
    }

    //启动service 方式2
    //
    private void bindService(){
        Intent intent = new Intent(Main3Activity.this,BindService.class);
        Log.i(TAG, "bindService()");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    private void unBindService(){
        Log.i(TAG, "unBindService() start....");
        if(flag == true){
            Log.i(TAG, "unBindService() flag");
            unbindService(conn);
            flag = false;
        }
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onServiceDisconnected()");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onServiceConnected()");
            BindService.MyBinder binder = (BindService.MyBinder)service;
            BindService bindService = binder.getService1();
            bindService.MyMethod();
            flag = true;
        }
    };
}


第二个Activity:
package com.example.administrator.androidtrainingtest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class Main4Activity extends AppCompatActivity {

    private boolean flag;
    private static final String TAG = "TestActivity";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        Button btnStart = (Button) findViewById(R.id.btnStart);

        Button btnStop = (Button) findViewById(R.id.btuStop);

        Button butStartActivity = (Button) findViewById(R.id.btnStartActivity);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动service 方式2
                bindService();
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //停止service 方式2
                unBindService();
            }
        });

    }

    //启动service 方式2
    //
    private void bindService(){
        Intent intent = new Intent(Main4Activity.this,BindService.class);
        Log.i(TAG, "bindService()");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    private void unBindService(){
        Log.i(TAG, "unBindService() start....");
        if(flag == true){
            Log.i(TAG, "unBindService() flag");
            unbindService(conn);
            flag = false;
        }
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onServiceDisconnected()");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onServiceConnected()");
            BindService.MyBinder binder = (BindService.MyBinder)service;
            BindService bindService = binder.getService1();
            bindService.MyMethod();
            flag = true;
        }
    };

}

Service:
package com.example.administrator.androidtrainingtest;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BindService extends Service {
    private static final String TAG = "BindService";
    private MyBinder myBinder = new MyBinder();
    public void MyMethod(){
        Log.i(TAG, "BindService-->MyMethod()");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "BindService-->onBind()");
        return myBinder;
    }

    public class MyBinder extends Binder {

        public BindService getService1(){
            return BindService.this;
        }
    }



    @Override
    public void onCreate() {
        Log.i(TAG, "BindService-->onCreate()");
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(TAG, "BindService-->onStart()");
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "BindService-->onDestroy()");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "BindService-->onUnbind()");
        return super.onUnbind(intent);
    }

}
两次绑定及解除绑定的结果:
09-07 19:08:40.458 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: bindService()
09-07 19:08:40.468 9536-9536/com.example.administrator.androidtrainingtest I/BindService: BindService-->onCreate()
09-07 19:08:40.488 9536-9536/com.example.administrator.androidtrainingtest I/BindService: BindService-->onBind()
09-07 19:08:40.498 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: onServiceConnected()
09-07 19:08:40.498 9536-9536/com.example.administrator.androidtrainingtest I/BindService: BindService-->MyMethod()
09-07 19:08:43.961 9536-9536/com.example.administrator.androidtrainingtest I/Timeline: Timeline: Activity_launch_request time:20965521
09-07 19:08:44.071 9536-9536/com.example.administrator.androidtrainingtest D/ActivityThreadInjector: clearCachedDrawables.
09-07 19:08:44.262 9536-9581/com.example.administrator.androidtrainingtest D/OpenGLRenderer: endAllActiveAnimators on 0xb4f90580 (RippleDrawable) with handle 0xa520db60
09-07 19:08:44.272 9536-9536/com.example.administrator.androidtrainingtest I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3dcf5808 time:20965832
09-07 19:08:45.943 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: bindService()
09-07 19:08:45.963 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: onServiceConnected()
09-07 19:08:45.963 9536-9536/com.example.administrator.androidtrainingtest I/BindService: BindService-->MyMethod()
09-07 19:08:48.426 9536-9547/com.example.administrator.androidtrainingtest I/art: Debugger is no longer active
09-07 19:09:17.444 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: unBindService() start....
09-07 19:09:17.444 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: unBindService() flag
09-07 19:09:21.658 9536-9536/com.example.administrator.androidtrainingtest I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@178fe5a8 time:21003228
09-07 19:09:24.120 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: unBindService() start....
09-07 19:09:24.120 9536-9536/com.example.administrator.androidtrainingtest I/TestActivity: unBindService() flag
09-07 19:09:24.131 9536-9536/com.example.administrator.androidtrainingtest I/BindService: BindService-->onUnbind()
09-07 19:09:24.131 9536-9536/com.example.administrator.androidtrainingtest I/BindService: BindService-->onDestroy()
09-07 19:09:27.043 9536-9547/com.example.administrator.androidtrainingtest I/art: Debugger is no longer active


你可能感兴趣的:(Android,JAVA)