android 取消蓝牙配对框 实现自动配对

来源:互联网 发布:amdcpu超频软件 编辑:程序博客网 时间:2024/04/27 22:01

我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,Android.bluetoothdevice 下 action_pair_request ,没有定义这个,开始困扰了我一点时间,实现难度:是否能进入那个广播响应。

 

 

定义了一个类,这个是网上的可以直接用

//================================================================================================================================

[java] view plain copy
  1. package zicox.esc;  
  2.   
  3. import java.lang.reflect.Method;  
  4. import java.lang.reflect.Field;  
  5.   
  6.   
  7. import android.bluetooth.BluetoothAdapter;  
  8. import android.bluetooth.BluetoothDevice;  
  9. import android.util.Log;  
  10.   
  11. public class ClsUtils   
  12. {  
  13.     /** 
  14.      * 与设备配对 参考源码:platform/packages/apps/Settings.git 
  15.      * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java 
  16.      */  
  17.     static public boolean createBond(Class btClass, BluetoothDevice btDevice)  
  18.     throws Exception  
  19.     {  
  20.         Method createBondMethod = btClass.getMethod("createBond");  
  21.         Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
  22.         return returnValue.booleanValue();  
  23.     }  
  24.    
  25.     /** 
  26.      * 与设备解除配对 参考源码:platform/packages/apps/Settings.git 
  27.      * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java 
  28.      */  
  29.     static public boolean removeBond(Class btClass, BluetoothDevice btDevice)  
  30.             throws Exception  
  31.     {  
  32.         Method removeBondMethod = btClass.getMethod("removeBond");  
  33.         Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);  
  34.         return returnValue.booleanValue();  
  35.     }  
  36.    
  37.     static public boolean setPin(Class btClass, BluetoothDevice btDevice,  
  38.             String str) throws Exception  
  39.     {  
  40.         try  
  41.         {  
  42.             Method removeBondMethod = btClass.getDeclaredMethod("setPin",  
  43.                     new Class[]  
  44.                     {byte[].class});  
  45.             Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,  
  46.                     new Object[]  
  47.                     {str.getBytes()});  
  48.             Log.e("returnValue""" + returnValue);  
  49.         }  
  50.         catch (SecurityException e)  
  51.         {  
  52.             // throw new RuntimeException(e.getMessage());  
  53.             e.printStackTrace();  
  54.         }  
  55.         catch (IllegalArgumentException e)  
  56.         {  
  57.             // throw new RuntimeException(e.getMessage());  
  58.             e.printStackTrace();  
  59.         }  
  60.         catch (Exception e)  
  61.         {  
  62.             // TODO Auto-generated catch block  
  63.             e.printStackTrace();  
  64.         }  
  65.         return true;  
  66.    
  67.     }  
  68.    
  69.     // 取消用户输入  
  70.     static public boolean cancelPairingUserInput(Class btClass,  
  71.             BluetoothDevice device)  
  72.    
  73.     throws Exception  
  74.     {  
  75.         Method createBondMethod = btClass.getMethod("cancelPairingUserInput");  
  76.         // cancelBondProcess()  
  77.         Boolean returnValue = (Boolean) createBondMethod.invoke(device);  
  78.         return returnValue.booleanValue();  
  79.     }  
  80.    
  81.     // 取消配对  
  82.     static public boolean cancelBondProcess(Class btClass,  
  83.             BluetoothDevice device)  
  84.    
  85.     throws Exception  
  86.     {  
  87.         Method createBondMethod = btClass.getMethod("cancelBondProcess");  
  88.         Boolean returnValue = (Boolean) createBondMethod.invoke(device);  
  89.         return returnValue.booleanValue();  
  90.     }  
  91.    
  92.     /** 
  93.      * 
  94.      * @param clsShow 
  95.      */  
  96.     static public void printAllInform(Class clsShow)  
  97.     {  
  98.         try  
  99.         {  
  100.             // 取得所有方法  
  101.             Method[] hideMethod = clsShow.getMethods();  
  102.             int i = 0;  
  103.             for (; i < hideMethod.length; i++)  
  104.             {  
  105.                 Log.e("method name", hideMethod[i].getName() + ";and the i is:"  
  106.                         + i);  
  107.             }  
  108.             // 取得所有常量  
  109.             Field[] allFields = clsShow.getFields();  
  110.             for (i = 0; i < allFields.length; i++)  
  111.             {  
  112.                 Log.e("Field name", allFields[i].getName());  
  113.             }  
  114.         }  
  115.         catch (SecurityException e)  
  116.         {  
  117.             // throw new RuntimeException(e.getMessage());  
  118.             e.printStackTrace();  
  119.         }  
  120.         catch (IllegalArgumentException e)  
  121.         {  
  122.             // throw new RuntimeException(e.getMessage());  
  123.             e.printStackTrace();  
  124.         }  
  125.         catch (Exception e)  
  126.         {  
  127.             // TODO Auto-generated catch block  
  128.             e.printStackTrace();  
  129.         }  
  130.     }  
  131.           
  132.       
  133.     static public boolean pair(String strAddr, String strPsw)  
  134.     {  
  135.         boolean result = false;  
  136.         BluetoothAdapter bluetoothAdapter = BluetoothAdapter  
  137.                 .getDefaultAdapter();  
  138.    
  139.         bluetoothAdapter.cancelDiscovery();  
  140.    
  141.         if (!bluetoothAdapter.isEnabled())  
  142.         {  
  143.             bluetoothAdapter.enable();  
  144.         }  
  145.    
  146.         if (!BluetoothAdapter.checkBluetoothAddress(strAddr))  
  147.         { // 检查蓝牙地址是否有效  
  148.    
  149.             Log.d("mylog""devAdd un effient!");  
  150.         }  
  151.    
  152.         BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);  
  153.    
  154.         if (device.getBondState() != BluetoothDevice.BOND_BONDED)  
  155.         {  
  156.             try  
  157.             {  
  158.                 Log.d("mylog""NOT BOND_BONDED");  
  159.                 ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对  
  160.                 ClsUtils.createBond(device.getClass(), device);  
  161. //                remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice  
  162.                 result = true;  
  163.             }  
  164.             catch (Exception e)  
  165.             {  
  166.                 // TODO Auto-generated catch block  
  167.    
  168.                 Log.d("mylog""setPiN failed!");  
  169.                 e.printStackTrace();  
  170.             } //  
  171.    
  172.         }  
  173.         else  
  174.         {  
  175.             Log.d("mylog""HAS BOND_BONDED");  
  176.             try  
  177.             {  
  178.                 ClsUtils.createBond(device.getClass(), device);  
  179.                 ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对  
  180.                 ClsUtils.createBond(device.getClass(), device);  
  181. //                remoteDevice = device; // 如果绑定成功,就直接把这个设备对象传给全局的remoteDevice  
  182.                 result = true;  
  183.             }  
  184.             catch (Exception e)  
  185.             {  
  186.                 // TODO Auto-generated catch block  
  187.                 Log.d("mylog""setPiN failed!");  
  188.                 e.printStackTrace();  
  189.             }  
  190.         }  
  191.         return result;  
  192.     }  
  193. }  


//================================================================================================================================

 

还有一部分 activity

//================================================================================================================================

 

[java] view plain copy
  1. package zicox.esc;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.lang.reflect.Method;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8. import java.util.UUID;  
  9.   
  10. import android.app.Activity;  
  11. import android.bluetooth.BluetoothAdapter;  
  12. import android.bluetooth.BluetoothDevice;  
  13. import android.bluetooth.BluetoothSocket;  
  14. import android.content.BroadcastReceiver;  
  15. import android.content.Context;  
  16. import android.content.Intent;  
  17. import android.content.IntentFilter;  
  18. import android.os.Bundle;  
  19. import android.util.Log;  
  20. import android.view.View;  
  21. import android.widget.AdapterView;  
  22. import android.widget.ArrayAdapter;  
  23. import android.widget.Button;  
  24. import android.widget.ListView;  
  25. import android.widget.Toast;  
  26. import android.widget.ToggleButton;  
  27.   
  28.   
  29. public class Demo_ad_escActivity extends Activity  
  30. {  
  31.     //---------------------------------------------------  
  32.     public static String ErrorMessage;  
  33.     Button btnSearch, btnDis, btnExit;  
  34.     ToggleButton tbtnSwitch;    
  35.     ListView lvBTDevices;    
  36.     ArrayAdapter<String> adtDevices;    
  37.     List<String> lstDevices = new ArrayList<String>();    
  38.     BluetoothAdapter btAdapt;    
  39.     public static BluetoothSocket btSocket;   
  40.     //---------------------------------------------------  
  41.       
  42.     public void onCreate(Bundle savedInstanceState) {  
  43.         super.onCreate(savedInstanceState);  
  44.         setContentView(R.layout.main);  
  45.       //  if(!ListBluetoothDevice())finish();  
  46.         Button Button1 = (Button) findViewById(R.id.button1);  
  47.         ErrorMessage = "";  
  48.   
  49.         //---------------------------------------------------  
  50.         btnSearch = (Button) this.findViewById(R.id.btnSearch);    
  51.         btnSearch.setOnClickListener(new ClickEvent());    
  52.         btnExit = (Button) this.findViewById(R.id.btnExit);    
  53.         btnExit.setOnClickListener(new ClickEvent());    
  54.         btnDis = (Button) this.findViewById(R.id.btnDis);    
  55.         btnDis.setOnClickListener(new ClickEvent());    
  56.         // ToogleButton设置    
  57.         tbtnSwitch = (ToggleButton) this.findViewById(R.id.toggleButton1);    
  58.         tbtnSwitch.setOnClickListener(new ClickEvent());  
  59.         // ListView及其数据源 适配器    
  60.         lvBTDevices = (ListView) this.findViewById(R.id.listView1);    
  61.         adtDevices = new ArrayAdapter<String>(this,    
  62.                 android.R.layout.simple_list_item_1, lstDevices);    
  63.         lvBTDevices.setAdapter(adtDevices);    
  64.         lvBTDevices.setOnItemClickListener(new ItemClickEvent());    
  65.           
  66.         btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能    
  67.           
  68.         if (btAdapt.isEnabled())   
  69.             tbtnSwitch.setChecked(false);    
  70.         else   
  71.             tbtnSwitch.setChecked(true);      
  72.          
  73.           // 注册Receiver来获取蓝牙设备相关的结果   
  74.         String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";  
  75.         IntentFilter intent = new IntentFilter();    
  76.         intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果    
  77.         intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);    
  78.         intent.addAction(ACTION_PAIRING_REQUEST);  
  79.         intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);    
  80.         intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);    
  81.         registerReceiver(searchDevices, intent);    
  82.           
  83.         Button1.setOnClickListener(new Button.OnClickListener()  
  84.         {  
  85.             public void onClick(View arg0)  
  86.             {  
  87.     //          Print1(SelectedBDAddress);  
  88.             }  
  89.         });  
  90.     }  
  91.   
  92. //---------------------------------------------------  
  93.       
  94.     private BroadcastReceiver searchDevices = new BroadcastReceiver() {    
  95.             
  96.         public void onReceive(Context context, Intent intent) {    
  97.             String action = intent.getAction();    
  98.             Bundle b = intent.getExtras();    
  99.             Object[] lstName = b.keySet().toArray();    
  100.     
  101.             // 显示所有收到的消息及其细节    
  102.             for (int i = 0; i < lstName.length; i++) {    
  103.                 String keyName = lstName[i].toString();    
  104.                 Log.e(keyName, String.valueOf(b.get(keyName)));    
  105.             }    
  106.             BluetoothDevice device = null;    
  107.             // 搜索设备时,取得设备的MAC地址    
  108.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {    
  109.                 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    
  110.                 if (device.getBondState() == BluetoothDevice.BOND_NONE) {    
  111.                     String str = "未配对|" + device.getName() + "|"    
  112.                             + device.getAddress();    
  113.                     if (lstDevices.indexOf(str) == -1)// 防止重复添加    
  114.                         lstDevices.add(str); // 获取设备名称和mac地址    
  115.                     adtDevices.notifyDataSetChanged();   
  116.                       
  117.                       
  118.                     try {  
  119.                         ClsUtils.setPin(device.getClass(),device,"0000");  
  120.                     } catch (Exception e) {  
  121.                         // TODO Auto-generated catch block  
  122.                         e.printStackTrace();  
  123.                     }  
  124.                     try {  
  125.                         ClsUtils.cancelPairingUserInput(device.getClass(), device);  
  126.                     } catch (Exception e) {  
  127.                         // TODO Auto-generated catch block  
  128.                         e.printStackTrace();  
  129.                     }  
  130.   
  131.                 }    
  132.             }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){    
  133.                 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    
  134.                 switch (device.getBondState()) {    
  135.                 case BluetoothDevice.BOND_BONDING:    
  136.                     Log.d("BlueToothTestActivity""正在配对......");    
  137.                     break;    
  138.                 case BluetoothDevice.BOND_BONDED:    
  139.                     Log.d("BlueToothTestActivity""完成配对");    
  140.                     connect(device);//连接设备    
  141.                     break;    
  142.                 case BluetoothDevice.BOND_NONE:    
  143.                     Log.d("BlueToothTestActivity""取消配对");    
  144.                 default:    
  145.                     break;    
  146.                 }    
  147.             }    
  148.               
  149.               
  150.             if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST"))  
  151.             {  
  152.                   
  153.                 Log.e("tag11111111111111111111111""ddd");  
  154.                 BluetoothDevice btDevice = intent  
  155.                         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  156.        
  157.                 // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");  
  158.                 // device.setPin(pinBytes);  
  159.               
  160.                 try  
  161.                 {  
  162.                     ClsUtils.setPin(btDevice.getClass(), btDevice, "0000"); // 手机和蓝牙采集器配对  
  163.                     ClsUtils.createBond(btDevice.getClass(), btDevice);  
  164.                     ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);  
  165.                 }  
  166.                 catch (Exception e)  
  167.                 {  
  168.                     // TODO Auto-generated catch block  
  169.                     e.printStackTrace();  
  170.                 }  
  171.             }  
  172.         }  
  173.     };  
  174.       
  175.     class ItemClickEvent implements AdapterView.OnItemClickListener {    
  176.             
  177.         @Override    
  178.         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,    
  179.                 long arg3) {    
  180.             if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();    
  181.             String str = lstDevices.get(arg2);    
  182.             String[] values = str.split("\\|");    
  183.             String address = values[2];    
  184.             Log.e("address", values[2]);    
  185.             BluetoothDevice btDev = btAdapt.getRemoteDevice(address);    
  186.             try {    
  187.                 Boolean returnValue = false;    
  188.                 if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {    
  189.                     //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);    
  190. //                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");    
  191. //                    Log.d("BlueToothTestActivity", "开始配对");    
  192. //                    returnValue = (Boolean) createBondMethod.invoke(btDev);    
  193.                     ClsUtils.pair(address, "0000");  
  194.                     showMessage("here");  
  195.                 }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){    
  196.                     connect(btDev);    
  197.                 }    
  198.             } catch (Exception e) {    
  199.                 e.printStackTrace();    
  200.             }    
  201.         }    
  202.     }    
  203.         
  204.     private void connect(BluetoothDevice btDev) {   
  205.         final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");  
  206.         UUID uuid = SPP_UUID;    
  207.         try {    
  208.             btSocket = btDev.createRfcommSocketToServiceRecord(uuid);    
  209.             Log.d("BlueToothTestActivity""开始连接...");    
  210.             btSocket.connect();    
  211.         } catch (IOException e) {    
  212.             // TODO Auto-generated catch block    
  213.             e.printStackTrace();    
  214.         }    
  215.     }    
  216.     
  217.     class ClickEvent implements View.OnClickListener {    
  218.         @Override    
  219.         public void onClick(View v) {    
  220.             if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果    
  221.             {    
  222.                 if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启    
  223.                     Toast.makeText(Demo_ad_escActivity.this"请先打开蓝牙"1000).show();                    return;    
  224.                 }    
  225.                 if (btAdapt.isDiscovering())    
  226.                     btAdapt.cancelDiscovery();    
  227.                 lstDevices.clear();    
  228.                 Object[] lstDevice = btAdapt.getBondedDevices().toArray();    
  229.                 for (int i = 0; i < lstDevice.length; i++) {    
  230.                     BluetoothDevice device = (BluetoothDevice) lstDevice[i];    
  231.                     String str = "已配对|" + device.getName() + "|"    
  232.                             + device.getAddress();    
  233.                     lstDevices.add(str); // 获取设备名称和mac地址    
  234.                     adtDevices.notifyDataSetChanged();    
  235.                 }    
  236.                 setTitle("本机蓝牙地址:" + btAdapt.getAddress());    
  237.                 btAdapt.startDiscovery();    
  238.             } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭    
  239.                 if (tbtnSwitch.isChecked() == false)    
  240.                     btAdapt.enable();    
  241.     
  242.                 else if (tbtnSwitch.isChecked() == true)    
  243.                     btAdapt.disable();    
  244.             } else if (v == btnDis)// 本机可以被搜索    
  245.             {    
  246.                 Intent discoverableIntent = new Intent(    
  247.                         BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);    
  248.                 discoverableIntent.putExtra(    
  249.                         BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);    
  250.                 startActivity(discoverableIntent);    
  251.             } else if (v == btnExit) {    
  252.                 try {    
  253.                     if (btSocket != null)    
  254.                         btSocket.close();    
  255.                 } catch (IOException e) {    
  256.                     e.printStackTrace();    
  257.                 }    
  258.                 Demo_ad_escActivity.this.finish();    
  259.             }    
  260.         }    
  261.     }   
  262.     
  263.     @Override    
  264.     protected void onDestroy() {    
  265.         this.unregisterReceiver(searchDevices);    
  266.         super.onDestroy();    
  267.         android.os.Process.killProcess(android.os.Process.myPid());    
  268.     }    
  269.     public void showMessage(String str)  
  270.     {  
  271.         Toast.makeText(this,str, Toast.LENGTH_LONG).show();  
  272.     }  
  273.       
  274. }  


//==============================================================================================

0 0
原创粉丝点击