service bound()

Service bound 一

service 绑定有三种实现方式:

1. 直接继承Binder类实现。

      条件: 同一应用,同一进程

2. 使用Messenger实现。

      条件:要在不同的进程间通信,这种方式不用考虑线程安全性。(单线程操作时使用)

3. 使用AIDL实现。

      条件:要在不同的进程间通信,并且需要多线程处理。要考虑线程之间的安全性。


下面是继承Binder类实现的例子;

具体步骤:

  • 在service中创建Binder实例
  • onBind() 返回Binder实例
  • 在client,实现ConnectionService类,获取Binder 对象。


---创建在service中创建Binder实例

	private LocalBinderExample binder = new LocalBinderExample();
	
	/**
	 * 其他组件绑定service的时候会返回Binder实例
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}
	
	public class LocalBinderExample extends Binder{
		
		public LocalServiceExample getService(){
			return LocalServiceExample.this ; //返回service
		}
		
	}


service有定义一个共有方法,为了在其他组件中调用。

	
	/**
	 * 其他的组件通过service可以调用
	 */
	public String getServiceName(){
		return LocalServiceExample.this.getClass().getName() ;
	}
	


--- onBind() 返回Binder实例

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

---在client,实现ConnectionService类,获取Binder 对象。

package com.hualu.serviceexample.bindinsampleapplicationprocesses;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.hualu.serviceexample.R;
import com.hualu.serviceexample.bindinsampleapplicationprocesses.LocalServiceExample.LocalBinderExample;

public class LocalServiceExampleActivity extends Activity implements OnClickListener{

	private Button bound ;
	private TextView text ;
	private LocalServiceExample mService ;
	
	private boolean bBound = false ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_binder_same_application_processes) ;
		bound = (Button)this.findViewById(R.id.bound) ;
		text = (TextView)this.findViewById(R.id.text) ;
		bound.setOnClickListener(this) ;
		
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bound:
			bindService(new Intent("com.hualu.serviceexample.BIND_SAME_APPLICATION_PROCESSES_SERVICE"), conn, Context.BIND_AUTO_CREATE) ; //绑定service
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mService != null){
						text.setText(mService.getServiceName()) ;
					}
				}
			}, 1000) ;
			
			break;

		default:
			break;
		}
	}
	
	private ServiceConnection  conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			bBound = false ;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinderExample binder = (LocalBinderExample)service ;
			mService = binder.getService() ;
			bBound = true ;
		}
	};
	
	
	protected void onStop() {
		super.onPause() ;
		if(bBound){
			unbindService(conn) ;
		}
	};
}


service的全部代码

package com.hualu.serviceexample.bindinsampleapplicationprocesses;

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

/**
 * @author Administrator
 *
 */

public class LocalServiceExample extends Service {

	private LocalBinderExample binder = new LocalBinderExample();
	
	/**
	 * 其他组件绑定service的时候会返回Binder实例
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}
	
	public class LocalBinderExample extends Binder{
		
		public LocalServiceExample getService(){
			return LocalServiceExample.this ; //返回service
		}
		
	}
	
	/**
	 * 其他的组件通过service可以调用
	 */
	public String getServiceName(){
		return LocalServiceExample.this.getClass().getName() ;
	}
	

}

Layout文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

    <Button
        android:id="@+id/bound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/text"
        android:text="@string/bound" />
	
</RelativeLayout>


manifest中关于activity和service的声明:

<activity android:name=".bindinsampleapplicationprocesses.LocalServiceExampleActivity">
       		<intent-filter>
       		    <action android:name="com.hualu.serviceexample.BIND_SAME_APPLICATION_PROCESSES"></action>
       		    <category android:name="android.intent.category.DEFAULT"></category>
       		</intent-filter>
        </activity>
        <service android:name=".bindinsampleapplicationprocesses.LocalServiceExample">
            <intent-filter>
                <action android:name="com.hualu.serviceexample.BIND_SAME_APPLICATION_PROCESSES_SERVICE"></action>
            </intent-filter>
        </service>





原文地址:https://www.cnblogs.com/xinyuyuanm/p/3002601.html