BluetoothConnectActivityReceiver.java:監聽藍牙配對的廣播 代碼: package com.imte.Broadcast; import com.imte.utils.ClsUtils; import com.itme.ActivityClass.R; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.util.Log; import android.widget.Toast; public class BluetoothConnectActivityReceiver extends BroadcastReceiver { String strPsw = "123456"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals( "android.bluetooth.device.action.PAIRING_REQUEST")) { BluetoothDevice btDevice = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); try { ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手機和藍牙採集的裝置配對 ClsUtils.createBond(btDevice.getClass(), btDevice); ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice); Toast.makeText( context, context.getResources().getString( R.string.bluetooth_connect_success), Toast.LENGTH_SHORT); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); // Thread thread=new Thread(strPsw); // thread. } } } } ClsUtils.java? package com.imte.utils; /************************************ 藍牙配對函數 * **************/ import java.lang.reflect.Field; import java.lang.reflect.Method; import android.bluetooth.BluetoothDevice; import android.util.Log; public class ClsUtils { /** * 與設備配對 參考源碼: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(); } /** * 與設備解除配對 參考源碼:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ static public boolean removeBond(Class btClass, BluetoothDevice btDevice) throws Exception { Method removeBondMethod = btClass.getMethod("removeBond"); Boolean returnValue = (Boolean) removeBondMethod.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()}); Log.e("returnValue", "" + returnValue); } 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; } // 取消用戶輸入 static public boolean cancelPairingUserInput(Class btClass, BluetoothDevice device) throws Exception { Method createBondMethod = btClass.getMethod("cancelPairingUserInput"); // cancelBondProcess() Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue(); } // 取消配對 static public boolean cancelBondProcess(Class btClass, BluetoothDevice device) throws Exception { Method createBondMethod = btClass.getMethod("cancelBondProcess"); Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue(); } /** * * @param clsShow */ static public void printAllInform(Class clsShow) { try { // 取得全部方法 Method[] hideMethod = clsShow.getMethods(); int i = 0; for (; i < hideMethod.length; i++) { Log.e("method name", hideMethod[i].getName() + ";and the i is:" + i); } // 取得全部常量 Field[] allFields = clsShow.getFields(); for (i = 0; i < allFields.length; i++) { Log.e("Field name", allFields[i].getName()); } } 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(); } } } 最後就是MainActivity,用一個按鈕來實現自動配對,代碼以下: package com.itme.ActivityClass; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.imte.utils.ClsUtils; public class MainActivity extends Activity implements OnClickListener{ /** Called when the activity is first created. */ private static BluetoothDevice remoteDevice=null; private Button btn_autopair=null; final static String ACTION_BLUETOOTHBC="android.bluetooth.device.action.PAIRING_REQUEST"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn_autopair=(Button)findViewById(R.id.btn_autopair); btn_autopair.setOnClickListener(this); } public static boolean pair(String strAddr, String strPsw) { boolean result = false; //藍牙設備適配器 BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); //取消發現當前設備的過程 bluetoothAdapter.cancelDiscovery(); if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) { // 檢查藍牙地址是否有效 Log.d("mylog", "devAdd un effient!"); } //由藍牙設備地址得到另外一藍牙設備對象 BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { try { Log.d("mylog", "NOT BOND_BONDED"); ClsUtils.setPin(device.getClass(), device, strPsw); // 手機和藍牙採集的裝置配對 ClsUtils.createBond(device.getClass(), device); // ClsUtils.cancelPairingUserInput(device.getClass(), device); remoteDevice = device; // 配對完畢就把這個設備對象傳給全局的remoteDevice result = true; } catch (Exception e) { // TODO Auto-generated catch block Log.d("mylog", "setPiN failed!"); e.printStackTrace(); } // } else { Log.d("mylog", "HAS BOND_BONDED"); try { //ClsUtils這個類的的如下靜態方法都是經過反射機制獲得須要的方法 ClsUtils.createBond(device.getClass(), device);//建立綁定 ClsUtils.setPin(device.getClass(), device, strPsw); // 手機和藍牙的裝置配對 ClsUtils.createBond(device.getClass(), device); // ClsUtils.cancelPairingUserInput(device.getClass(), device); remoteDevice = device; // 若是綁定成功,就直接把這個設備對象傳給全局的remoteDevice result = true; } catch (Exception e) { // TODO Auto-generated catch block Log.d("mylog", "setPiN failed!"); e.printStackTrace(); } } return result; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_autopair: if (pair("94:DB:46:2B:A1:82", "123456")) {//pair的第一個參數是要配對的藍牙地址,第二個參數是配對時預先設置的密鑰 Log.i("aaron", remoteDevice.getAddress()); } break; default: break; } } } 叮咚..如題的功能就實現了。。。 項目源代碼下載地址: http://download.csdn.net/detail/huangrangg12/4578242