zoukankan      html  css  js  c++  java
  • android蓝牙主动发起配对实例

    1. package cn.madfinger.core;  
    2.   
    3. import java.io.IOException;  
    4. import java.lang.reflect.Method;  
    5. import java.util.ArrayList;  
    6. import java.util.List;  
    7. import java.util.UUID;  
    8.   
    9. import android.app.Activity;  
    10. import android.bluetooth.BluetoothAdapter;  
    11. import android.bluetooth.BluetoothDevice;  
    12. import android.bluetooth.BluetoothSocket;  
    13. import android.content.BroadcastReceiver;  
    14. import android.content.Context;  
    15. import android.content.Intent;  
    16. import android.content.IntentFilter;  
    17. import android.os.Bundle;  
    18. import android.util.Log;  
    19. import android.view.View;  
    20. import android.widget.AdapterView;  
    21. import android.widget.ArrayAdapter;  
    22. import android.widget.Button;  
    23. import android.widget.ListView;  
    24. import android.widget.Toast;  
    25. import android.widget.ToggleButton;  
    26.   
    27. public class BlueToothTestActivity extends Activity {  
    28.     //该UUID表示串口服务  
    29.     //请参考文章<a href="http://wiley.iteye.com/blog/1179417">http://wiley.iteye.com/blog/1179417</a>  
    30.     static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";  
    31.     Button btnSearch, btnDis, btnExit;  
    32.     ToggleButton tbtnSwitch;  
    33.     ListView lvBTDevices;  
    34.     ArrayAdapter<String> adtDevices;  
    35.     List<String> lstDevices = new ArrayList<String>();  
    36.     BluetoothAdapter btAdapt;  
    37.     public static BluetoothSocket btSocket;  
    38.   
    39.     @Override  
    40.     public void onCreate(Bundle savedInstanceState) {  
    41.         super.onCreate(savedInstanceState);  
    42.         setContentView(R.layout.main);  
    43.         // Button 设置  
    44.         btnSearch = (Button) this.findViewById(R.id.btnSearch);  
    45.         btnSearch.setOnClickListener(new ClickEvent());  
    46.         btnExit = (Button) this.findViewById(R.id.btnExit);  
    47.         btnExit.setOnClickListener(new ClickEvent());  
    48.         btnDis = (Button) this.findViewById(R.id.btnDis);  
    49.         btnDis.setOnClickListener(new ClickEvent());  
    50.   
    51.         // ToogleButton设置  
    52.         tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);  
    53.         tbtnSwitch.setOnClickListener(new ClickEvent());  
    54.   
    55.         // ListView及其数据源 适配器  
    56.         lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);  
    57.         adtDevices = new ArrayAdapter<String>(this,  
    58.                 android.R.layout.simple_list_item_1, lstDevices);  
    59.         lvBTDevices.setAdapter(adtDevices);  
    60.         lvBTDevices.setOnItemClickListener(new ItemClickEvent());  
    61.   
    62.         btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能  
    63.   
    64.         // ========================================================  
    65.         // modified by wiley  
    66.         /* 
    67.          * if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示 
    68.          * tbtnSwitch.setChecked(false); else if (btAdapt.getState() == 
    69.          * BluetoothAdapter.STATE_ON) tbtnSwitch.setChecked(true); 
    70.          */  
    71.         if (btAdapt.isEnabled()) {  
    72.             tbtnSwitch.setChecked(false);  
    73.         } else {  
    74.             tbtnSwitch.setChecked(true);  
    75.         }  
    76.         // ============================================================  
    77.         // 注册Receiver来获取蓝牙设备相关的结果  
    78.         IntentFilter intent = new IntentFilter();  
    79.         intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果  
    80.         intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
    81.         intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
    82.         intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
    83.         registerReceiver(searchDevices, intent);  
    84.     }  
    85.   
    86.     private BroadcastReceiver searchDevices = new BroadcastReceiver() {  
    87.   
    88.         public void onReceive(Context context, Intent intent) {  
    89.             String action = intent.getAction();  
    90.             Bundle b = intent.getExtras();  
    91.             Object[] lstName = b.keySet().toArray();  
    92.   
    93.             // 显示所有收到的消息及其细节  
    94.             for (int i = 0; i < lstName.length; i++) {  
    95.                 String keyName = lstName[i].toString();  
    96.                 Log.e(keyName, String.valueOf(b.get(keyName)));  
    97.             }  
    98.             BluetoothDevice device = null;  
    99.             // 搜索设备时,取得设备的MAC地址  
    100.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
    101.                 device = intent  
    102.                         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
    103.                 if (device.getBondState() == BluetoothDevice.BOND_NONE) {  
    104.                     String str = "未配对|" + device.getName() + "|"  
    105.                             + device.getAddress();  
    106.                     if (lstDevices.indexOf(str) == -1)// 防止重复添加  
    107.                         lstDevices.add(str); // 获取设备名称和mac地址  
    108.                     adtDevices.notifyDataSetChanged();  
    109.                 }  
    110.             }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){  
    111.                 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
    112.                 switch (device.getBondState()) {  
    113.                 case BluetoothDevice.BOND_BONDING:  
    114.                     Log.d("BlueToothTestActivity", "正在配对......");  
    115.                     break;  
    116.                 case BluetoothDevice.BOND_BONDED:  
    117.                     Log.d("BlueToothTestActivity", "完成配对");  
    118.                     connect(device);//连接设备  
    119.                     break;  
    120.                 case BluetoothDevice.BOND_NONE:  
    121.                     Log.d("BlueToothTestActivity", "取消配对");  
    122.                 default:  
    123.                     break;  
    124.                 }  
    125.             }  
    126.               
    127.         }  
    128.     };  
    129.   
    130.     @Override  
    131.     protected void onDestroy() {  
    132.         this.unregisterReceiver(searchDevices);  
    133.         super.onDestroy();  
    134.         android.os.Process.killProcess(android.os.Process.myPid());  
    135.     }  
    136.   
    137.     class ItemClickEvent implements AdapterView.OnItemClickListener {  
    138.   
    139.         @Override  
    140.         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
    141.                 long arg3) {  
    142.             if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();  
    143.             String str = lstDevices.get(arg2);  
    144.             String[] values = str.split("\|");  
    145.             String address = values[2];  
    146.             Log.e("address", values[2]);  
    147.             BluetoothDevice btDev = btAdapt.getRemoteDevice(address);  
    148.             try {  
    149.                 Boolean returnValue = false;  
    150.                 if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {  
    151.                     //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);  
    152.                     Method createBondMethod = BluetoothDevice.class  
    153.                             .getMethod("createBond");  
    154.                     Log.d("BlueToothTestActivity", "开始配对");  
    155.                     returnValue = (Boolean) createBondMethod.invoke(btDev);  
    156.                       
    157.                 }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){  
    158.                     connect(btDev);  
    159.                 }  
    160.             } catch (Exception e) {  
    161.                 e.printStackTrace();  
    162.             }  
    163.   
    164.         }  
    165.   
    166.     }  
    167.       
    168.     private void connect(BluetoothDevice btDev) {  
    169.         UUID uuid = UUID.fromString(SPP_UUID);  
    170.         try {  
    171.             btSocket = btDev.createRfcommSocketToServiceRecord(uuid);  
    172.             Log.d("BlueToothTestActivity", "开始连接...");  
    173.             btSocket.connect();  
    174.         } catch (IOException e) {  
    175.             // TODO Auto-generated catch block  
    176.             e.printStackTrace();  
    177.         }  
    178.     }  
    179.   
    180.     class ClickEvent implements View.OnClickListener {  
    181.         @Override  
    182.         public void onClick(View v) {  
    183.             if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果  
    184.             {  
    185.                 if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启  
    186.                     Toast.makeText(BlueToothTestActivity.this, "请先打开蓝牙", 1000)  
    187.                             .show();  
    188.                     return;  
    189.                 }  
    190.                 if (btAdapt.isDiscovering())  
    191.                     btAdapt.cancelDiscovery();  
    192.                 lstDevices.clear();  
    193.                 Object[] lstDevice = btAdapt.getBondedDevices().toArray();  
    194.                 for (int i = 0; i < lstDevice.length; i++) {  
    195.                     BluetoothDevice device = (BluetoothDevice) lstDevice[i];  
    196.                     String str = "已配对|" + device.getName() + "|"  
    197.                             + device.getAddress();  
    198.                     lstDevices.add(str); // 获取设备名称和mac地址  
    199.                     adtDevices.notifyDataSetChanged();  
    200.                 }  
    201.                 setTitle("本机蓝牙地址:" + btAdapt.getAddress());  
    202.                 btAdapt.startDiscovery();  
    203.             } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭  
    204.                 if (tbtnSwitch.isChecked() == false)  
    205.                     btAdapt.enable();  
    206.   
    207.                 else if (tbtnSwitch.isChecked() == true)  
    208.                     btAdapt.disable();  
    209.             } else if (v == btnDis)// 本机可以被搜索  
    210.             {  
    211.                 Intent discoverableIntent = new Intent(  
    212.                         BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
    213.                 discoverableIntent.putExtra(  
    214.                         BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  
    215.                 startActivity(discoverableIntent);  
    216.             } else if (v == btnExit) {  
    217.                 try {  
    218.                     if (btSocket != null)  
    219.                         btSocket.close();  
    220.                 } catch (IOException e) {  
    221.                     e.printStackTrace();  
    222.                 }  
    223.                 BlueToothTestActivity.this.finish();  
    224.             }  
    225.         }  
    226.   
    227.     }  
    228. }  
  • 相关阅读:
    从MSFT Project中同步数据到PSA
    TracingService. 码农debug的救星
    Business Workflow Flow 最后一个stage阶段触发Exist
    BPF form 中的readonly 只读字段自动unblock
    Windows Server 使用fiddler中抓取IIS的请求
    Dynamics 365 CE 的快捷键 Shortcut
    Dynamics 365 online 服务器保护机制 server limitation
    在后端C#中 call web api 关联lookup 和 GUID
    PSA 需要 Sales Order中 读取的最低权限 read minimal privilege
    python学习笔记10:分析程序性能cProfile
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/6514533.html
Copyright © 2011-2022 走看看