Android 取消蓝牙配对框实现自动配对功能
我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,Android.bluetoothdevice下action_pair_request,没有定义这个,开始困扰了我一点时间,实现难度:是否能进入那个广播响应
定义了一个类,这个是网上的可以直接用
packagezicox.esc; importjava.lang.reflect.Method; importjava.lang.reflect.Field; importandroid.bluetooth.BluetoothAdapter; importandroid.bluetooth.BluetoothDevice; importandroid.util.Log; publicclassClsUtils { /** *与设备配对参考源码:platform/packages/apps/Settings.Git */Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ staticpublicbooleancreateBond(ClassbtClass,BluetoothDevicebtDevice) throwsExceptionwww.nhooo.com { MethodcreateBondMethod=btClass.getMethod("createBond"); BooleanreturnValue=(Boolean)createBondMethod.invoke(btDevice); returnreturnValue.booleanValue(); } /** *与设备解除配对参考源码:platform/packages/apps/Settings.git */Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ staticpublicbooleanremoveBond(ClassbtClass,BluetoothDevicebtDevice) throwsException { MethodremoveBondMethod=btClass.getMethod("removeBond"); BooleanreturnValue=(Boolean)removeBondMethod.invoke(btDevice); returnreturnValue.booleanValue(); } staticpublicbooleansetPin(ClassbtClass,BluetoothDevicebtDevice, Stringstr)throwsException { try { MethodremoveBondMethod=btClass.getDeclaredMethod("setPin", newClass[] {byte[].class}); BooleanreturnValue=(Boolean)removeBondMethod.invoke(btDevice, newObject[] {str.getBytes()}); Log.e("returnValue",""+returnValue); } catch(SecurityExceptione) { //thrownewRuntimeException(e.getMessage()); e.printStackTrace(); } catch(IllegalArgumentExceptione) { //thrownewRuntimeException(e.getMessage()); e.printStackTrace(); } catch(Exceptione) { //TODOAuto-generatedcatchblock e.printStackTrace(); } returntrue; } //取消用户输入 staticpublicbooleancancelPairingUserInput(ClassbtClass, BluetoothDevicedevice) throwsException { MethodcreateBondMethod=btClass.getMethod("cancelPairingUserInput"); //cancelBondProcess() BooleanreturnValue=(Boolean)createBondMethod.invoke(device); returnreturnValue.booleanValue(); } //取消配对 staticpublicbooleancancelBondProcess(ClassbtClass, BluetoothDevicedevice) throwsException { MethodcreateBondMethod=btClass.getMethod("cancelBondProcess"); BooleanreturnValue=(Boolean)createBondMethod.invoke(device); returnreturnValue.booleanValue(); } /** * *@paramclsShow */ staticpublicvoidprintAllInform(ClassclsShow) { try { //取得所有方法 Method[]hideMethod=clsShow.getMethods(); inti=0; for(;i<hideMethod.length;i++) { Log.e("methodname",hideMethod[i].getName()+";andtheiis:" +i); } //取得所有常量 Field[]allFields=clsShow.getFields(); for(i=0;i<allFields.length;i++) { Log.e("Fieldname",allFields[i].getName()); } } catch(SecurityExceptione) { //thrownewRuntimeException(e.getMessage()); e.printStackTrace(); } catch(IllegalArgumentExceptione) { //thrownewRuntimeException(e.getMessage()); e.printStackTrace(); } catch(Exceptione) { //TODOAuto-generatedcatchblock e.printStackTrace(); } } staticpublicbooleanpair(StringstrAddr,StringstrPsw) { booleanresult=false; BluetoothAdapterbluetoothAdapter=BluetoothAdapter .getDefaultAdapter(); bluetoothAdapter.cancelDiscovery(); if(!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } if(!BluetoothAdapter.checkBluetoothAddress(strAddr)) {//检查蓝牙地址是否有效 Log.d("mylog","devAdduneffient!"); } BluetoothDevicedevice=bluetoothAdapter.getRemoteDevice(strAddr); if(device.getBondState()!=BluetoothDevice.BOND_BONDED) { try { Log.d("mylog","NOTBOND_BONDED"); ClsUtils.setPin(device.getClass(),device,strPsw);//手机和蓝牙采集器配对 ClsUtils.createBond(device.getClass(),device); //remoteDevice=device;//配对完毕就把这个设备对象传给全局的remoteDevice result=true; } catch(Exceptione) { //TODOAuto-generatedcatchblock Log.d("mylog","setPiNfailed!"); e.printStackTrace(); }// } else { Log.d("mylog","HASBOND_BONDED"); try { ClsUtils.createBond(device.getClass(),device); ClsUtils.setPin(device.getClass(),device,strPsw);//手机和蓝牙采集器配对 ClsUtils.createBond(device.getClass(),device); //remoteDevice=device;//如果绑定成功,就直接把这个设备对象传给全局的remoteDevice result=true; } catch(Exceptione) { //TODOAuto-generatedcatchblock Log.d("mylog","setPiNfailed!"); e.printStackTrace(); } } returnresult; } } //================================================================================================================================
还有一部分activity
//================================================================================================================================ packagezicox.esc; importjava.io.IOException; importjava.io.UnsupportedEncodingException; importjava.lang.reflect.Method; importjava.util.ArrayList; importjava.util.List; importjava.util.UUID; importandroid.app.Activity; importandroid.bluetooth.BluetoothAdapter; importandroid.bluetooth.BluetoothDevice; importandroid.bluetooth.BluetoothSocket; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.content.IntentFilter; importandroid.os.Bundle; importandroid.util.Log; importandroid.view.View; importandroid.widget.AdapterView; importandroid.widget.ArrayAdapter; importandroid.widget.Button; importandroid.widget.ListView; importandroid.widget.Toast; importandroid.widget.ToggleButton; publicclassDemo_ad_escActivityextendsActivity { //--------------------------------------------------- publicstaticStringErrorMessage; ButtonbtnSearch,btnDis,btnExit; ToggleButtontbtnSwitch; ListViewlvBTDevices; ArrayAdapter<String>adtDevices; List<String>lstDevices=newArrayList<String>(); BluetoothAdapterbtAdapt; publicstaticBluetoothSocketbtSocket; //--------------------------------------------------- publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); //if(!ListBluetoothDevice())finish(); ButtonButton1=(Button)findViewById(R.id.button1); ErrorMessage=""; //--------------------------------------------------- btnSearch=(Button)this.findViewById(R.id.btnSearch); btnSearch.setOnClickListener(newClickEvent()); btnExit=(Button)this.findViewById(R.id.btnExit); btnExit.setOnClickListener(newClickEvent()); btnDis=(Button)this.findViewById(R.id.btnDis); btnDis.setOnClickListener(newClickEvent()); //ToogleButton设置 tbtnSwitch=(ToggleButton)this.findViewById(R.id.toggleButton1); tbtnSwitch.setOnClickListener(newClickEvent()); //ListView及其数据源适配器 lvBTDevices=(ListView)this.findViewById(R.id.listView1); adtDevices=newArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lstDevices); lvBTDevices.setAdapter(adtDevices); lvBTDevices.setOnItemClickListener(newItemClickEvent()); btAdapt=BluetoothAdapter.getDefaultAdapter();//初始化本机蓝牙功能 if(btAdapt.isEnabled()) tbtnSwitch.setChecked(false); else tbtnSwitch.setChecked(true); //注册Receiver来获取蓝牙设备相关的结果 StringACTION_PAIRING_REQUEST="android.bluetooth.device.action.PAIRING_REQUEST"; IntentFilterintent=newIntentFilter(); intent.addAction(BluetoothDevice.ACTION_FOUND);//用BroadcastReceiver来取得搜索结果 intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intent.addAction(ACTION_PAIRING_REQUEST); intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(searchDevices,intent); Button1.setOnClickListener(newButton.OnClickListener() { publicvoidonClick(Viewarg0) { //Print1(SelectedBDAddress); } }); } //--------------------------------------------------- privateBroadcastReceiversearchDevices=newBroadcastReceiver(){ publicvoidonReceive(Contextcontext,Intentintent){ Stringaction=intent.getAction(); Bundleb=intent.getExtras(); Object[]lstName=b.keySet().toArray(); //显示所有收到的消息及其细节 for(inti=0;i<lstName.length;i++){ StringkeyName=lstName[i].toString(); Log.e(keyName,String.valueOf(b.get(keyName))); } BluetoothDevicedevice=null; //搜索设备时,取得设备的MAC地址 if(BluetoothDevice.ACTION_FOUND.equals(action)){ device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if(device.getBondState()==BluetoothDevice.BOND_NONE){ Stringstr="未配对|"+device.getName()+"|" +device.getAddress(); if(lstDevices.indexOf(str)==-1)//防止重复添加 lstDevices.add(str);//获取设备名称和mac地址 adtDevices.notifyDataSetChanged(); try{ ClsUtils.setPin(device.getClass(),device,"0000"); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } try{ ClsUtils.cancelPairingUserInput(device.getClass(),device); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } }elseif(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){ device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); switch(device.getBondState()){ caseBluetoothDevice.BOND_BONDING: Log.d("BlueToothTestActivity","正在配对......"); break; caseBluetoothDevice.BOND_BONDED: Log.d("BlueToothTestActivity","完成配对"); connect(device);//连接设备 break; caseBluetoothDevice.BOND_NONE: Log.d("BlueToothTestActivity","取消配对"); default: break; } } if(intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) { Log.e("tag11111111111111111111111","ddd"); BluetoothDevicebtDevice=intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //byte[]pinBytes=BluetoothDevice.convertPinToBytes("1234"); //device.setPin(pinBytes); try { ClsUtils.setPin(btDevice.getClass(),btDevice,"0000");//手机和蓝牙采集器配对 ClsUtils.createBond(btDevice.getClass(),btDevice); ClsUtils.cancelPairingUserInput(btDevice.getClass(),btDevice); } catch(Exceptione) { //TODOAuto-generatedcatchblock e.printStackTrace(); } } } }; classItemClickEventimplementsAdapterView.OnItemClickListener{ @Override publicvoidonItemClick(AdapterView<?>arg0,Viewarg1,intarg2, longarg3){ if(btAdapt.isDiscovering())btAdapt.cancelDiscovery(); Stringstr=lstDevices.get(arg2); String[]values=str.split("\\|"); Stringaddress=values[2]; Log.e("address",values[2]); BluetoothDevicebtDev=btAdapt.getRemoteDevice(address); try{ BooleanreturnValue=false; if(btDev.getBondState()==BluetoothDevice.BOND_NONE){ //利用反射方法调用BluetoothDevice.createBond(BluetoothDeviceremoteDevice); //MethodcreateBondMethod=BluetoothDevice.class.getMethod("createBond"); //Log.d("BlueToothTestActivity","开始配对"); //returnValue=(Boolean)createBondMethod.invoke(btDev); ClsUtils.pair(address,"0000"); showMessage("here"); }elseif(btDev.getBondState()==BluetoothDevice.BOND_BONDED){ connect(btDev); } }catch(Exceptione){ e.printStackTrace(); } } } privatevoidconnect(BluetoothDevicebtDev){ finalUUIDSPP_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); UUIDuuid=SPP_UUID; try{ btSocket=btDev.createRfcommSocketToServiceRecord(uuid); Log.d("BlueToothTestActivity","开始连接..."); btSocket.connect(); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } classClickEventimplementsView.OnClickListener{ @Override publicvoidonClick(Viewv){ if(v==btnSearch)//搜索蓝牙设备,在BroadcastReceiver显示结果 { if(btAdapt.getState()==BluetoothAdapter.STATE_OFF){//如果蓝牙还没开启 Toast.makeText(Demo_ad_escActivity.this,"请先打开蓝牙",1000).show();return; } if(btAdapt.isDiscovering()) btAdapt.cancelDiscovery(); lstDevices.clear(); Object[]lstDevice=btAdapt.getBondedDevices().toArray(); for(inti=0;i<lstDevice.length;i++){ BluetoothDevicedevice=(BluetoothDevice)lstDevice[i]; Stringstr="已配对|"+device.getName()+"|" +device.getAddress(); lstDevices.add(str);//获取设备名称和mac地址 adtDevices.notifyDataSetChanged(); } setTitle("本机蓝牙地址:"+btAdapt.getAddress()); btAdapt.startDiscovery(); }elseif(v==tbtnSwitch){//本机蓝牙启动/关闭 if(tbtnSwitch.isChecked()==false) btAdapt.enable(); elseif(tbtnSwitch.isChecked()==true) btAdapt.disable(); }elseif(v==btnDis)//本机可以被搜索 { IntentdiscoverableIntent=newIntent( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300); startActivity(discoverableIntent); }elseif(v==btnExit){ try{ if(btSocket!=null) btSocket.close(); }catch(IOExceptione){ e.printStackTrace(); } Demo_ad_escActivity.this.finish(); } } } @Override protectedvoidonDestroy(){ this.unregisterReceiver(searchDevices); super.onDestroy(); android.os.Process.killProcess(android.os.Process.myPid()); } publicvoidshowMessage(Stringstr) { Toast.makeText(this,str,Toast.LENGTH_LONG).show(); } }
以上所述是小编给大家介绍的Android取消蓝牙配对框实现自动配对功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!