Binder 进程通信

Binder用于进程通信,就像我们普通的的程序需要调用系统的服务,或者调用自己的服务。Binder 一种构架, 提供服务端接口, Binder驱动,服务端接口三个模块。


原理: 客户端获得服务端的Binder引用, 然后调用服务端的方法。具体见下面代码。


一、先看看调用自己的服务

package com.jc.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;

import com.jc.service.Bridge;

public class MainActivity extends Activity {

	
	private MyServiceConnection myServiceConnection;
	
	private Bridge bridge;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void start(View v) {
    	Intent intent = new Intent();
    	intent.setAction("com.jc.service.jj");
    	myServiceConnection = new MyServiceConnection();
    	bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
    }
    
    public void startmethod(View v) {
    	try {
    		System.out.println("调用方法");
    		bridge.callBanzheng();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
    }
    
    private class MyServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//service就是刚才MyService绑定返回的对象引用
			System.out.println("获得桥梁");
			bridge = Bridge.Stub.asInterface(service); //这里bridge就相当于manager
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
    	
    }
}


package com.jc.service;

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

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("绑定成功");
		return new MyBinder();
	}
	
	public void banzheng() {
		System.out.println("开始办证");
	}
	
	private class MyBinder extends Bridge.Stub {

		@Override
		public void callBanzheng() throws RemoteException {
			// TODO Auto-generated method stub
			banzheng();
		}
		
	}

}

下面是android提供的aidl机制。


/*
 * This file is auto-generated.  DO NOT MODIFY.
 */
package com.jc.service;

public interface Bridge extends android.os.IInterface {
	/** Local-side IPC implementation stub class. */
	public static abstract class Stub extends android.os.Binder implements
			com.jc.service.Bridge {
		private static final java.lang.String DESCRIPTOR = "com.jc.service.Bridge";

		/** Construct the stub at attach it to the interface. */
		public Stub() {
			this.attachInterface(this, DESCRIPTOR);
		}

		/**
		 * Cast an IBinder object into an com.jc.service.Bridge interface,
		 * generating a proxy if needed.
		 */
		public static com.jc.service.Bridge asInterface(android.os.IBinder obj) {
			if ((obj == null)) {
				return null;
			}
			android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
			if (((iin != null) && (iin instanceof com.jc.service.Bridge))) {
				return ((com.jc.service.Bridge) iin);
			}
			return new com.jc.service.Bridge.Stub.Proxy(obj);
		}

		@Override
		public android.os.IBinder asBinder() {
			return this;
		}

		@Override
		public boolean onTransact(int code, android.os.Parcel data,
				android.os.Parcel reply, int flags)
				throws android.os.RemoteException {
			switch (code) {
			case INTERFACE_TRANSACTION: {
				reply.writeString(DESCRIPTOR);
				return true;
			}
			case TRANSACTION_callBanzheng: {
				data.enforceInterface(DESCRIPTOR);
				this.callBanzheng();
				reply.writeNoException();
				return true;
			}
			}
			return super.onTransact(code, data, reply, flags);
		}

		private static class Proxy implements com.jc.service.Bridge {
			private android.os.IBinder mRemote;

			Proxy(android.os.IBinder remote) {
				mRemote = remote;
			}

			@Override
			public android.os.IBinder asBinder() {
				return mRemote;
			}

			public java.lang.String getInterfaceDescriptor() {
				return DESCRIPTOR;
			}

			@Override
			public void callBanzheng() throws android.os.RemoteException {
				android.os.Parcel _data = android.os.Parcel.obtain();
				android.os.Parcel _reply = android.os.Parcel.obtain();
				try {
					_data.writeInterfaceToken(DESCRIPTOR);
					mRemote.transact(Stub.TRANSACTION_callBanzheng, _data,
							_reply, 0);
					_reply.readException();
				} finally {
					_reply.recycle();
					_data.recycle();
				}
			}
		}

		static final int TRANSACTION_callBanzheng = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
	}

	public void callBanzheng() throws android.os.RemoteException;
}

其实就是调用服务端的IBinder mRemote.transact() 服务端就调用onTransact


二、再看看调用系统的服务

  @Override
    public Object getSystemService(String name) {
        if (WINDOW_SERVICE.equals(name)) {
            return WindowManagerImpl.getDefault();
        } else if (LAYOUT_INFLATER_SERVICE.equals(name)) {
            synchronized (mSync) {
                LayoutInflater inflater = mLayoutInflater;
                if (inflater != null) {
                    return inflater;
                }
                mLayoutInflater = inflater =
                    PolicyManager.makeNewLayoutInflater(getOuterContext());
                return inflater;
            }
        } else if (ACTIVITY_SERVICE.equals(name)) {
            return getActivityManager();
        } else if (INPUT_METHOD_SERVICE.equals(name)) {
            return InputMethodManager.getInstance(this);
        } else if (ALARM_SERVICE.equals(name)) {
            return getAlarmManager();
        } else if (ACCOUNT_SERVICE.equals(name)) {
            return getAccountManager();
        } else if (POWER_SERVICE.equals(name)) {
            return getPowerManager();
        } else if (CONNECTIVITY_SERVICE.equals(name)) {
            return getConnectivityManager();
        } else if (THROTTLE_SERVICE.equals(name)) {
            return getThrottleManager();
        } else if (WIFI_SERVICE.equals(name)) {
            return getWifiManager();
        } else if (NOTIFICATION_SERVICE.equals(name)) {
            return getNotificationManager();
        } else if (KEYGUARD_SERVICE.equals(name)) {
            return new KeyguardManager();
        } else if (ACCESSIBILITY_SERVICE.equals(name)) {
            return AccessibilityManager.getInstance(this);
        } else if (LOCATION_SERVICE.equals(name)) {
            return getLocationManager();
        } else if (SEARCH_SERVICE.equals(name)) {
            return getSearchManager();
        } else if (SENSOR_SERVICE.equals(name)) {
            return getSensorManager();
        } else if (STORAGE_SERVICE.equals(name)) {
            return getStorageManager();
        } else if (USB_SERVICE.equals(name)) {
            return getUsbManager();
        } else if (VIBRATOR_SERVICE.equals(name)) {
            return getVibrator();
        } else if (STATUS_BAR_SERVICE.equals(name)) {
            synchronized (mSync) {
                if (mStatusBarManager == null) {
                    mStatusBarManager = new StatusBarManager(getOuterContext());
                }
                return mStatusBarManager;
            }
        } else if (AUDIO_SERVICE.equals(name)) {
            return getAudioManager();
        } else if (TELEPHONY_SERVICE.equals(name)) {
            return getTelephonyManager();
        } else if (CLIPBOARD_SERVICE.equals(name)) {
            return getClipboardManager();
        } else if (WALLPAPER_SERVICE.equals(name)) {
            return getWallpaperManager();
        } else if (DROPBOX_SERVICE.equals(name)) {
            return getDropBoxManager();
        } else if (DEVICE_POLICY_SERVICE.equals(name)) {
            return getDevicePolicyManager();
        } else if (UI_MODE_SERVICE.equals(name)) {
            return getUiModeManager();
        } else if (DOWNLOAD_SERVICE.equals(name)) {
            return getDownloadManager();
        } else if (NFC_SERVICE.equals(name)) {
            return getNfcManager();
        }

        return null;
    }

这个获取系统服务, 里面是个switch判断。下面随便分析一个系统服务。


    private WifiManager getWifiManager()
    {
        synchronized (sSync) {
            if (sWifiManager == null) {
                IBinder b = ServiceManager.getService(WIFI_SERVICE);
                IWifiManager service = IWifiManager.Stub.asInterface(b);
                sWifiManager = new WifiManager(service, mMainThread.getHandler());
            }
        }
        return sWifiManager;
    }

从ServiceManager中获取系统服务


    public static IBinder getService(String name) {
        try {
            IBinder service = sCache.get(name);
            if (service != null) {
                return service;
            } else {
                return getIServiceManager().getService(name);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "error in getService", e);
        }
        return null;
    }

    private static IServiceManager getIServiceManager() {
        if (sServiceManager != null) {
            return sServiceManager;
        }
        //BinderInternal.getContextObject()获取系统唯一ServiceManager的IBinder。 底层源码是C/C++实现。
        // Find the service manager
        sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject()); //将Binder转化为ServiceManager
        return sServiceManager;
    }

Manager的作用, 为什么这里都要将IBinder对象装饰为Manager对象。

1. 这样做方便管理, 方便调用。

2. 隐藏一些“暴力的api方法”。(比如挂断电话)



展开阅读全文

没有更多推荐了,返回首页