bluetooth


MainActivity 

Java代码   收藏代码
  1. package com.zzl.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.   
  10. public class MainActivity extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.           
  17.         Button btn = (Button) findViewById(R.id.button1);  
  18.           
  19.         btn.setOnClickListener(new OnClickListener() {  
  20.               
  21.             @Override  
  22.             public void onClick(View v) {  
  23.                 Intent intent = new Intent(getApplication(),BTConnectActivity.class);  
  24.                 startActivity(intent);  
  25.                 finish();  
  26.             }  
  27.         });  
  28.     }  
  29. }  


BTConnectActivity 
Java代码   收藏代码
  1. package com.zzl.test; 
  2.   
  3. import java.io.IOException;  
  4. import java.util.UUID;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.content.Intent;  
  10. import android.content.Context;  
  11. import android.content.BroadcastReceiver;  
  12. import android.content.IntentFilter;  
  13.   
  14. import android.widget.AdapterView;  
  15.   
  16. import android.widget.ListView;  
  17. import android.widget.ArrayAdapter;  
  18.   
  19. import android.widget.Toast;  
  20. import android.util.Log;  
  21. import android.view.View;  
  22.   
  23. import android.bluetooth.BluetoothAdapter;  
  24. import android.bluetooth.BluetoothDevice;  
  25. import android.bluetooth.BluetoothSocket;  
  26. public class BTConnectActivity extends Activity {  
  27.   
  28.     // private static final String TAG = "BTConnectActivity";  
  29.   
  30.     /** Called when the activity is first created. */  
  31.     public static final int REQUEST_ENABLE_BT = 8807;  
  32.     public BroadcastReceiver mBTReceiver;  
  33.     public static BluetoothSocket mBTSocket;  
  34.     public BluetoothAdapter mBTAdapter;  
  35.     public BluetoothDevice mBTDevice;  
  36.     private ArrayAdapter<String> adtDvcs;  
  37.     private List<String> lstDvcsStr = new ArrayList<String>();  
  38.     private ListView lvDevicesList;  
  39.     @Override  
  40.     public void onCreate(Bundle savedInstanceState) {  
  41.         super.onCreate(savedInstanceState);  
  42.         setContentView(R.layout.btconnect);  
  43.   
  44.   
  45.         // 初始化 BluetoothAdapter  
  46.         mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // c  
  47.   
  48.         if (mBTAdapter == null) {  
  49.             Toast.makeText(BTConnectActivity.this"没有支持蓝牙的设备! ",  
  50.                     Toast.LENGTH_SHORT).show();  
  51.             this.finish();  
  52.         }  
  53.         if (!mBTAdapter.isEnabled()) {  
  54.             // Open a new dialog to ask user whether wanna open BT  
  55.             Toast.makeText(BTConnectActivity.this"请打开手机蓝牙后再重试! ",  
  56.                     Toast.LENGTH_SHORT).show();  
  57.             this.finish();  
  58.   
  59.             Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  60.             startActivityForResult(enabler, REQUEST_ENABLE_BT);  
  61.         }  
  62.         // 开启 BroadCast Receiver  
  63.         mBTReceiver = new BroadcastReceiver() {  
  64.             public void onReceive(Context context, Intent intent) {  
  65.                 String act = intent.getAction();  
  66.                 // To see whether the action is that already found devices  
  67.                 if (act.equals(BluetoothDevice.ACTION_FOUND)) {  
  68.                     // 如果发现一个设备,得到设备的对象  
  69.   
  70.   
  71.                     BluetoothDevice tmpDvc = intent  
  72.                             .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  73.                     // Put the name & address into a string  
  74.                     String tmpDvcStr = tmpDvc.getName() + "|"  
  75.                             + tmpDvc.getAddress();  
  76.                     if (lstDvcsStr.indexOf(tmpDvcStr) == -1) {  
  77.                         // Avoid duplicate add devices  
  78.                         lstDvcsStr.add(tmpDvcStr);  
  79.                         adtDvcs.notifyDataSetChanged();  
  80.                         Toast.makeText(BTConnectActivity.this"发现一个新设备",  
  81.                                 Toast.LENGTH_SHORT).show();  
  82.                     }  
  83.                 }  
  84.                 if (act.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {  
  85.                     Toast.makeText(BTConnectActivity.this"搜索完成!",  
  86.                             Toast.LENGTH_SHORT).show();  
  87.                 }  
  88.   
  89.                 if (act.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {  
  90.                     Toast.makeText(BTConnectActivity.this"开始搜索设备",  
  91.                             Toast.LENGTH_SHORT).show();  
  92.                 }  
  93.             }  
  94.         };  
  95.   
  96.         // 注册 broadcastReceiver  
  97.         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  98.         registerReceiver(mBTReceiver, filter);  
  99.         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);  
  100.         registerReceiver(mBTReceiver, filter);  
  101.         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  102.         registerReceiver(mBTReceiver, filter);  
  103.   
  104.         lvDevicesList = (ListView) findViewById(R.id.lvDevicesList);  
  105.   
  106.         adtDvcs = new ArrayAdapter<String>(this,  
  107.                 android.R.layout.simple_list_item_1, lstDvcsStr);  
  108.         lvDevicesList.setAdapter(adtDvcs);  
  109.   
  110.         if (mBTAdapter.isDiscovering()) {  
  111.             Toast.makeText(BTConnectActivity.this"正在搜索......",  
  112.                     Toast.LENGTH_SHORT).show();  
  113.         } else {  
  114.             lstDvcsStr.clear();  
  115.             adtDvcs.notifyDataSetChanged();  
  116.             mBTDevice = null;  
  117.             mBTAdapter.startDiscovery();  
  118.         }  
  119.   
  120.         // 在设备列表中创建单击事件  
  121.         lvDevicesList  
  122.                 .setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  123.                     public void onItemClick(AdapterView<?> arg0, View arg1,  
  124.                             int arg2, long arg3) {  
  125.                         if (mBTAdapter == null)  
  126.                             Toast.makeText(BTConnectActivity.this"没有搜索到蓝牙设备",  
  127.                                     Toast.LENGTH_SHORT).show();  
  128.                         else {  
  129.                             // 停止搜索  
  130.                             mBTAdapter.cancelDiscovery();  
  131.                             // 得到设备的地址  
  132.                             String str = lstDvcsStr.get(arg2);  
  133.                             String[] dvcValues = str.split("\\|");  
  134.                             String dvcAddr = dvcValues[1];  
  135.                             UUID dvcUUID = UUID  
  136.                                     .fromString("00001101-0000-1000-8000-00805F9B34FB");  
  137.                             mBTDevice = mBTAdapter.getRemoteDevice(dvcAddr);  
  138.                             // 连接设备  
  139.                             try {  
  140.                                 // 根据UUID创建并返回一个BluetoothSocket  
  141.                                 mBTSocket = mBTDevice  
  142.                                         .createRfcommSocketToServiceRecord(dvcUUID);  
  143.                                 mBTSocket.connect();  
  144.   
  145.                                 Intent intent = new Intent(getApplicationContext(),WriteActivity.class);  
  146.                                 startActivity(intent);  
  147.                                   
  148.                                   
  149.                             } catch (IOException e) {  
  150.                                 e.printStackTrace();  
  151.                             }  
  152.                         }  
  153.                     }  
  154.                 });  
  155.     }  
  156.   
  157.     public void onActivityResult(int RequestCode, int ResultCode, Intent data) {  
  158.         Log.i("BTConnectActivity""RequestCode is " + RequestCode  
  159.                 + ", ResultCode is " + ResultCode);  
  160.         switch (RequestCode) {  
  161.         case REQUEST_ENABLE_BT:  
  162.             if (ResultCode == RESULT_OK) {  
  163.                 Toast.makeText(this.getApplicationContext(), "蓝牙已连接!",  
  164.                         Toast.LENGTH_SHORT).show();  
  165.             } else if (ResultCode == RESULT_CANCELED) {  
  166.                 Toast.makeText(this.getApplicationContext(), "蓝牙连接被取消!",  
  167.                         Toast.LENGTH_SHORT).show();  
  168.             }  
  169.             break;  
  170.         }  
  171.     }  
  172.   
  173.     @Override  
  174.     protected void onDestroy() {  
  175.         try {  
  176.             mBTSocket.close();  
  177.         } catch (IOException e) {  
  178.             e.printStackTrace();  
  179.         }  
  180.         this.unregisterReceiver(mBTReceiver);  
  181.         super.onDestroy();  
  182.     }  
  183. }  

WriteActivity 
Java代码   收藏代码
  1. package com.zzl.test;  
  2. import android.app.Activity;  
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.os.Message;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.TextView;  
  12. import android.widget.Toast;  
  13.   
  14. public class WriteActivity extends Activity {  
  15.       
  16.       
  17.     private TextView tv;  
  18.     private BTReadThread mReadThread = new BTReadThread(50);  
  19.     private boolean enRead = false;   
  20.     private Handler handler = new Handler() {  
  21.   
  22.         @Override  
  23.         public void handleMessage(Message msg) {  
  24.   
  25.             switch (msg.what) {  
  26.             case 0:  
  27.                 tv.setText(msg.obj.toString());  
  28.                 break;  
  29.             }  
  30.         }  
  31.     };  
  32.     @Override  
  33.     public void onCreate(Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setContentView(R.layout.write);  
  36.         tv = (TextView) findViewById(R.id.tv);  
  37.         btint();  
  38.           
  39.     }  
  40.       
  41.       
  42.     /** 
  43.      * 开启读取蓝牙数据的线程 
  44.      */  
  45.     private void btint() {  
  46.         try {  
  47.             if (BTConnectActivity.mBTSocket.getInputStream() != null) {  
  48.                 enRead = true;  
  49.                 mReadThread.start();  
  50.             }  
  51.         } catch (Exception e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.     }  
  55.       
  56.       
  57.     /*** 
  58.      * 蓝牙操作 
  59.      */  
  60.     class BTReadThread extends Thread {  
  61.         private int wait = 50;// Time to wait  
  62.   
  63.         public BTReadThread(int wait) {  
  64.             this.wait = wait;  
  65.         }  
  66.           
  67.         public void stopThread(){  
  68.             enRead = false;  
  69.         }  
  70.   
  71.         public void run() {  
  72.             while (enRead) {  
  73.                 try {  
  74.                     if (BTConnectActivity.mBTSocket.getInputStream() != null) {  
  75.                         byte[] tmp = new byte[1024];  
  76.                         int len = BTConnectActivity.mBTSocket.getInputStream().read(tmp, 01024); // 卡  
  77.   
  78.                         if (len > 0) {  
  79.   
  80.                             String res = "";  
  81.                             for (int i = 0; i < tmp.length; i++) {  
  82.                                 String hex = Integer.toHexString(tmp[i] & 0xFF);  
  83.                                 if (hex.length() == 1) {  
  84.                                     hex = '0' + hex;  
  85.                                 }  
  86.                                 res += hex.toUpperCase();  
  87.                             }  
  88.   
  89.                             String strDES = res.substring(016);  
  90.                               
  91.                             Message message = handler.obtainMessage();  
  92.                             message.what = 0;  
  93.                             message.obj = strDES;  
  94.                             handler.sendMessage(message);  
  95.                         }  
  96.                     }  
  97.                     Thread.sleep(wait);  
  98.                 } catch (Exception e) {  
  99.                     e.printStackTrace();  
  100.                 }  
  101.             }  
  102.         }  
  103.     }  
  104. }  


记得添加权限: 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
<uses-permission android:name="android.permission.BLUETOOTH" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值