用bindService()启动Service的方式与生命周期

首先看看Google的官方API对bindService()的解释:

大致意思是:连接到一个应用的service上面,如果需要的话,创建它。这个定义会在你的应用程序和service之间产生一种依赖关系,给定的conn会接收到service对象当service被创建时,而且会被告之他是停止了还是重新启动了。这个service会被操作系统保留只要调用的context存在。举个例子,如果这个上下文是一个Activity,且这个Activity被停止了,这个service也不会被请求继续运行,直到这个Activity恢复以后,这个service才会被请求继续运行。

大概了解了一下bindService的使用方法、来看一个具体的实例:

文件结构:

接下来贴上主要的代码:

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button startButton, stopButton;
	private MyService myService;

	private ServiceConnection serviceConn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Log.v("Show_V", "onServiceDisconnected");
			myService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Log.v("Show_V", "onServiceConnected");
			myService = ((MyService.IBinderImple) service).getMyService();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		startButton = (Button) findViewById(R.id.startService);
		stopButton = (Button) findViewById(R.id.stopService);
		startButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, MyService.class);
				MainActivity.this.bindService(intent, serviceConn,
						Service.BIND_AUTO_CREATE);
			}
		});

		stopButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (myService != null) {
					unbindService(serviceConn);
					myService = null;
				}
			}
		});
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (myService != null) {
			unbindService(serviceConn);
			myService = null;
		}
	}
}
package com.example.servicetest;

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

public class MyService extends Service {

	public class IBinderImple extends Binder {
		public MyService getMyService() {
			Log.v("Show_V", "getMyService");
			return MyService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.v("Show_V", "onBind");
		return new IBinderImple();
	}

	@Override
	public void onRebind(Intent intent) {
		// TODO Auto-generated method stub
		super.onRebind(intent);
		Log.v("Show_V", "onRebind");
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Log.v("Show_V", "onUnbind");
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.v("Show_V", "onCreate");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.v("Show_V", "onDestroy");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v("Show_V", "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicetest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.servicetest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

</manifest>

主要代码如上,先运行一下程序,看看程序的运行结果,然后再来解释解释:

主界面是:


我们点击使用bindService方法启动Service的按钮,看logcat的显示结果:

继续点击启动按钮,logcat没有打印更多的信息,说明重复执行bindService()方法并不会触发任何回调函数。点击停止bindService按钮,Logcat的显示结果:


MainActivity里面的onStop()方法删去了,继续运行程序,点击启动,一切正常,跟上面的情况一样,当我点击返回按钮时,程序退出,有点不正常,不过logcat里面的打印结果还是跟上面的图一样。不过logcat里面抛出了错误,大概意思就是serviceConnection泄露。

我导出了LogCat内容如下图:


总结一下:

bindService()启动service的生命周期和调用bindService()方法的Activity的生命周期是一致的,也就是如果Activity如果结束了,那么Service也就结束了。Service和调用bindService()方法的进程是同生共死的。好的编程习惯,都是在ActivityonStop()方法中加上unBindService(ServiceConnection conn)代码,那样就不会抛出我上面的错误了。绑定service到当前的Activity中,使service跟当前的Activity保持状态上面的一致。


原文地址:https://www.cnblogs.com/vokie/p/3602088.html