Android Bluetooth Bluetoothスピーカーとイヤホンを接続するA 2 dpとHeadset Profile


Bluetooth検索はSPPプロトコルとの接続ネットワークルーチンが多く、詳しくは紹介されていませんが、公式ルーチンBluetoothChatは良い例です.ただし、すべてのBluetoothデバイスがSPPプロトコルをサポートしているわけではありません.A 2 dpとHeadsetプロトコルを接続するルーチンは多くありません.本明細書で説明する方法は、BluetoothスピーカーとBluetoothイヤホンの接続に特に適しています.原理は主に反射原理を利用してシステムapiを得て接続し、まずペアリング解除ペアリングボックスから弾き出す.
 /**
	  *      
	  */
	 private void doPair(){
		 mBluetoothAdapter.cancelDiscovery();
		 if (D) Log.d(TAG, "    ");
		//  
		 if(mDevice.getBondState()!= BluetoothDevice.BOND_BONDED){
			try {
				if (D) Log.d(TAG, "setPin 2 ...");
				BluetoothMethod.setPin(mDevice.getClass(), mDevice,"0000");
				if (D) Log.d(TAG, "createBond 2 ...");
				BluetoothMethod.createBond(mDevice.getClass(), mDevice);
			} catch (Exception e) {
				connectfailed();
				e.printStackTrace();
			}
		}else{
			setState(STATE_CONNECTING);
		}
	 }

setPin()とcreateBond()はandroidシステムのソース/frameworks/base/core/java/android/bluetooth/BluetoothDevice.java
に表示されます.反射呼び出しの方法でこの方法を得ることができ、
     /** 
     *           :platform/packages/apps/Settings.git 
     * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java 
     */  
    static public boolean createBond(Class btClass,BluetoothDevice btDevice) throws Exception {  
        Method createBondMethod = btClass.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  
static public boolean setPin(Class btClass, BluetoothDevice btDevice,
			String str) throws Exception
	{
		try
		{
			Method removeBondMethod = btClass.getDeclaredMethod("setPin",new Class[]{byte[].class});
			Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
					new Object[]
					{str.getBytes()});
		}
		catch (SecurityException e)
		{
			// throw new RuntimeException(e.getMessage());
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			// throw new RuntimeException(e.getMessage());
			e.printStackTrace();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;

	}

ペアリングが完了するとA 2 dpとHeadsetプロトコルを接続することができ、同様に反射的な方法でこの2つのプロトコルの接続と接続を切断する方法を得ることができる.
//A2DP    HeadSet
	static public boolean connect(Class btClass,BluetoothProfile proxy,BluetoothDevice btDevice) throws Exception {  
        Method connectMethod = btClass.getDeclaredMethod("connect", BluetoothDevice.class);       
        connectMethod.setAccessible(true);
        Boolean returnValue = (Boolean) connectMethod.invoke(proxy,btDevice);  
        return returnValue.booleanValue();  
    }
	
	static public boolean disconnect(Class btClass,BluetoothProfile proxy,BluetoothDevice btDevice) throws Exception {  
        Method disconnectMethod = btClass.getDeclaredMethod("disconnect", BluetoothDevice.class);     
        disconnectMethod.setAccessible(true);
        Boolean returnValue = (Boolean) disconnectMethod.invoke(proxy,btDevice);  
        return returnValue.booleanValue();  
    }

A 2 dpとHeadsetはBluetoothProfileというクラスに属し、サービス傍受の方法でA 2 dpとHeadset Profileに接続し、onBluetoothConnect()を実行すればよい.公式チュートリアルではBluetoothProfileの接続(working with Profiles)について詳しく説明している
 /** 
     * @Title:onBluetoothConnected 
     * @Description:      A2dp Headset  
     * @param: 
    */
    public void onBluetoothConnect(){
    	mBluetoothAdapter.getProfileProxy(this, mA2dpProfileListener, BluetoothProfile.A2DP);
    	//new BluetoothA2DP(this).request(this, mBluetoothAdapter);
    	mBluetoothAdapter.getProfileProxy(this, mHeadsetProfileListener, BluetoothProfile.HEADSET);
    	//new BluetoothHeadSetProfile(this).request(this, mBluetoothAdapter);
    }
    
   /** 
    * @Title:onBluetoothDisConnect 
    * @Description:  A2DP Headset      
    */
    public void onBluetoothDisConnect(BluetoothDevice device){
    	if(mBluetoothA2dp!=null){
	    	try {
				BluetoothMethod.disconnect(mBluetoothA2dp.getClass(),mBluetoothA2dp, device);
				mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, mBluetoothA2dp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if (D) Log.d(TAG, "close A2dp failed!!!");
				e.printStackTrace();
			}
    	}
    	if(mBluetoothHeadset!=null){
		   try {
				BluetoothMethod.disconnect(mBluetoothHeadset.getClass(),mBluetoothHeadset, device);
				mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);	
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if (D) Log.d(TAG, "close Headset failed!!!");
				e.printStackTrace();
			}
    	}
   }
    
    /** 
     * @Fields mA2dpProfileListener : A2dp      
     */ 
    private BluetoothProfile.ServiceListener mA2dpProfileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.A2DP) {
                mBluetoothA2dp = (BluetoothA2dp) proxy;
                if(mState == STATE_CONNECTING){
	                try {
						BluetoothMethod.connect(mBluetoothA2dp.getClass(),mBluetoothA2dp, mDevice);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						if (D) Log.d(TAG, "connect to A2dp failed!!!");
						mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, mBluetoothA2dp);
						e.printStackTrace();
					}
                }
            }
        }
        public void onServiceDisconnected(int profile) {
            if (profile == BluetoothProfile.A2DP) {
            	mBluetoothA2dp = null;
            }
        }
    };
    
    /** 
     * @Fields mHeadsetProfileListener : BluetoothHeadset      
     */ 
    private BluetoothProfile.ServiceListener mHeadsetProfileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.HEADSET) {
            	mBluetoothHeadset = (BluetoothHeadset) proxy;
            	if(mState == STATE_CONNECTING){
	            	try {
						BluetoothMethod.connect(mBluetoothHeadset.getClass(),mBluetoothHeadset, mDevice);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						if (D) Log.d(TAG, "connect to Headset failed!!!");
						mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
						e.printStackTrace();
					}
            	}
            }
        }
        public void onServiceDisconnected(int profile) {
            if (profile == BluetoothProfile.HEADSET) {
            	mBluetoothHeadset = null;
            }
        }
    };