的萨达

  1. public class BlueToothTestActivity extends Activity {  
  2.     //该UUID表示串口服务  
  3.     //请参考文章<a href="http://wiley.iteye.com/blog/1179417">http://wiley.iteye.com/blog/1179417</a>  
  4.     static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";  
  5.     Button btnSearch, btnDis, btnExit;  
  6.     ToggleButton tbtnSwitch;  
  7.     ListView lvBTDevices;  
  8.     ArrayAdapter<String> adtDevices;  
  9.     List<String> lstDevices = new ArrayList<String>();  
  10.     BluetoothAdapter btAdapt;  
  11.     public static BluetoothSocket btSocket;  
  12.   
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.main);  
  17.         // Button 设置  
  18.         btnSearch = (Button) this.findViewById(R.id.btnSearch);  
  19.         btnSearch.setOnClickListener(new ClickEvent());  
  20.         btnExit = (Button) this.findViewById(R.id.btnExit);  
  21.         btnExit.setOnClickListener(new ClickEvent());  
  22.         btnDis = (Button) this.findViewById(R.id.btnDis);  
  23.         btnDis.setOnClickListener(new ClickEvent());  
  24.   
  25.         // ToogleButton设置  
  26.         tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);  
  27.         tbtnSwitch.setOnClickListener(new ClickEvent());  
  28.   
  29.         // ListView及其数据源 适配器  
  30.         lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);  
  31.         adtDevices = new ArrayAdapter<String>(this,  
  32.                 android.R.layout.simple_list_item_1, lstDevices);  
  33.         lvBTDevices.setAdapter(adtDevices);  
  34.         lvBTDevices.setOnItemClickListener(new ItemClickEvent());  
  35.   
  36.         btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能  
  37.   
  38.         // ========================================================  
  39.         // modified by wiley  
  40.         /* 
  41.          * if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示 
  42.          * tbtnSwitch.setChecked(false); else if (btAdapt.getState() == 
  43.          * BluetoothAdapter.STATE_ON) tbtnSwitch.setChecked(true); 
  44.          */  
  45.         if (btAdapt.isEnabled()) {  
  46.             tbtnSwitch.setChecked(false);  
  47.         } else {  
  48.             tbtnSwitch.setChecked(true);  
  49.         }  
  50.         // ============================================================  
  51.         // 注册Receiver来获取蓝牙设备相关的结果  
  52.         IntentFilter intent = new IntentFilter();  
  53.         intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果  
  54.         intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
  55.         intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
  56.         intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
  57.         registerReceiver(searchDevices, intent);  
  58.     }  
  59.   
  60.     private BroadcastReceiver searchDevices = new BroadcastReceiver() {  
  61.   
  62.         public void onReceive(Context context, Intent intent) {  
  63.             String action = intent.getAction();  
  64.             Bundle b = intent.getExtras();  
  65.             Object[] lstName = b.keySet().toArray();  
  66.   
  67.             // 显示所有收到的消息及其细节  
  68.             for (int i = 0; i < lstName.length; i++) {  
  69.                 String keyName = lstName[i].toString();  
  70.                 Log.e(keyName, String.valueOf(b.get(keyName)));  
  71.             }  
  72.             BluetoothDevice device = null;  
  73.             // 搜索设备时,取得设备的MAC地址  
  74.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
  75.                 device = intent  
  76.                         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  77.                 if (device.getBondState() == BluetoothDevice.BOND_NONE) {  
  78.                     String str = "未配对|" + device.getName() + "|"  
  79.                             + device.getAddress();  
  80.                     if (lstDevices.indexOf(str) == -1)// 防止重复添加  
  81.                         lstDevices.add(str); // 获取设备名称和mac地址  
  82.                     adtDevices.notifyDataSetChanged();  
  83.                 }  
  84.             }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){  
  85.                 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  86.                 switch (device.getBondState()) {  
  87.                 case BluetoothDevice.BOND_BONDING:  
  88.                     Log.d("BlueToothTestActivity""正在配对......");  
  89.                     break;  
  90.                 case BluetoothDevice.BOND_BONDED:  
  91.                     Log.d("BlueToothTestActivity""完成配对");  
  92.                     connect(device);//连接设备  
  93.                     break;  
  94.                 case BluetoothDevice.BOND_NONE:  
  95.                     Log.d("BlueToothTestActivity""取消配对");  
  96.                 default:  
  97.                     break;  
  98.                 }  
  99.             }  
  100.               
  101.         }  
  102.     };  
  103.   
  104.     @Override  
  105.     protected void onDestroy() {  
  106.         this.unregisterReceiver(searchDevices);  
  107.         super.onDestroy();  
  108.         android.os.Process.killProcess(android.os.Process.myPid());  
  109.     }  
  110.   
  111.     class ItemClickEvent implements AdapterView.OnItemClickListener {  
  112.   
  113.         @Override  
  114.         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
  115.                 long arg3) {  
  116.             if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();  
  117.             String str = lstDevices.get(arg2);  
  118.             String[] values = str.split("\\|");  
  119.             String address = values[2];  
  120.             Log.e("address", values[2]);  
  121.             BluetoothDevice btDev = btAdapt.getRemoteDevice(address);  
  122.             try {  
  123.                 Boolean returnValue = false;  
  124.                 if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {  
  125.                     //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);  
  126.                     Method createBondMethod = BluetoothDevice.class  
  127.                             .getMethod("createBond");  
  128.                     Log.d("BlueToothTestActivity""开始配对");  
  129.                     returnValue = (Boolean) createBondMethod.invoke(btDev);  
  130.                       
  131.                 }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){  
  132.                     connect(btDev);  
  133.                 }  
  134.             } catch (Exception e) {  
  135.                 e.printStackTrace();  
  136.             }  
  137.   
  138.         }  
  139.   
  140.     }  
  141.       
  142.     private void connect(BluetoothDevice btDev) {  
  143.         UUID uuid = UUID.fromString(SPP_UUID);  
  144.         try {  
  145.             btSocket = btDev.createRfcommSocketToServiceRecord(uuid);  
  146.             Log.d("BlueToothTestActivity""开始连接...");  
  147.             btSocket.connect();  
  148.         } catch (IOException e) {  
  149.             // TODO Auto-generated catch block  
  150.             e.printStackTrace();  
  151.         }  
  152.     }  
  153.   
  154.     class ClickEvent implements View.OnClickListener {  
  155.         @Override  
  156.         public void onClick(View v) {  
  157.             if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果  
  158.             {  
  159.                 if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启  
  160.                     Toast.makeText(BlueToothTestActivity.this"请先打开蓝牙"1000)  
  161.                             .show();  
  162.                     return;  
  163.                 }  
  164.                 if (btAdapt.isDiscovering())  
  165.                     btAdapt.cancelDiscovery();  
  166.                 lstDevices.clear();  
  167.                 Object[] lstDevice = btAdapt.getBondedDevices().toArray();  
  168.                 for (int i = 0; i < lstDevice.length; i++) {  
  169.                     BluetoothDevice device = (BluetoothDevice) lstDevice[i];  
  170.                     String str = "已配对|" + device.getName() + "|"  
  171.                             + device.getAddress();  
  172.                     lstDevices.add(str); // 获取设备名称和mac地址  
  173.                     adtDevices.notifyDataSetChanged();  
  174.                 }  
  175.                 setTitle("本机蓝牙地址:" + btAdapt.getAddress());  
  176.                 btAdapt.startDiscovery();  
  177.             } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭  
  178.                 if (tbtnSwitch.isChecked() == false)  
  179.                     btAdapt.enable();  
  180.   
  181.                 else if (tbtnSwitch.isChecked() == true)  
  182.                     btAdapt.disable();  
  183.             } else if (v == btnDis)// 本机可以被搜索  
  184.             {  
  185.                 Intent discoverableIntent = new Intent(  
  186.                         BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  187.                 discoverableIntent.putExtra(  
  188.                         BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  
  189.                 startActivity(discoverableIntent);  
  190.             } else if (v == btnExit) {  
  191.                 try {  
  192.                     if (btSocket != null)  
  193.                         btSocket.close();  
  194.                 } catch (IOException e) {  
  195.                     e.printStackTrace();  
  196.                 }  
  197.                 BlueToothTestActivity.this.finish();  
  198.             }  
  199.         }  
  200.   
  201.     }  
  202. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值