zoukankan      html  css  js  c++  java
  • Android蓝牙通信具体解释

    蓝牙通信的大概过程例如以下:

    1。首先开启蓝牙

    2,搜索可用设备

    3,创建蓝牙socket。获取输入输出流

    4,读取和写入数据

    5。断开连接关闭蓝牙


    还要发送配对码发送进行推断!


    以下是全部的源码;不会非常难;认真看;

    SearchDeviceActivity.java

    [java] view plaincopy
    1. package com.hello.project;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.Iterator;  
    5. import java.util.List;  
    6. import java.util.Set;  
    7.   
    8. import android.app.Activity;  
    9. import android.app.AlertDialog;  
    10. import android.bluetooth.BluetoothAdapter;  
    11. import android.bluetooth.BluetoothDevice;  
    12. import android.content.BroadcastReceiver;  
    13. import android.content.Context;  
    14. import android.content.DialogInterface;  
    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.view.View.OnClickListener;  
    21. import android.widget.AdapterView;  
    22. import android.widget.AdapterView.OnItemClickListener;  
    23. import android.widget.ArrayAdapter;  
    24. import android.widget.Button;  
    25. import android.widget.ListView;  
    26.   
    27. public class SearchDeviceActivity extends Activity implements OnItemClickListener{  
    28.   
    29.   
    30.     private BluetoothAdapter blueadapter=null;  
    31.     private DeviceReceiver mydevice=new DeviceReceiver();  
    32.     private List<String> deviceList=new ArrayList<String>();  
    33.     private ListView deviceListview;  
    34.     private Button btserch;  
    35.     private ArrayAdapter<String> adapter;  
    36.     private boolean hasregister=false;  
    37.       
    38.     @Override  
    39.     protected void onCreate(Bundle savedInstanceState) {  
    40.         super.onCreate(savedInstanceState);  
    41.         setContentView(R.layout.finddevice);  
    42.         setView();  
    43.         setBluetooth();  
    44.           
    45.     }  
    46.       
    47.     private void setView(){  
    48.       
    49.         deviceListview=(ListView)findViewById(R.id.devicelist);  
    50.         adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, deviceList);  
    51.         deviceListview.setAdapter(adapter);  
    52.         deviceListview.setOnItemClickListener(this);  
    53.         btserch=(Button)findViewById(R.id.start_seach);  
    54.         btserch.setOnClickListener(new ClinckMonitor());  
    55.           
    56.     }  
    57.   
    58.     @Override  
    59.     protected void onStart() {  
    60.         //注冊蓝牙接收广播  
    61.         if(!hasregister){  
    62.             hasregister=true;  
    63.             IntentFilter filterStart=new IntentFilter(BluetoothDevice.ACTION_FOUND);      
    64.             IntentFilter filterEnd=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);      
    65.             registerReceiver(mydevice, filterStart);  
    66.             registerReceiver(mydevice, filterEnd);  
    67.         }         
    68.         super.onStart();  
    69.     }  
    70.   
    71.     @Override  
    72.     protected void onDestroy() {  
    73.         if(blueadapter!=null&&blueadapter.isDiscovering()){  
    74.             blueadapter.cancelDiscovery();  
    75.         }  
    76.         if(hasregister){  
    77.             hasregister=false;  
    78.             unregisterReceiver(mydevice);  
    79.         }  
    80.         super.onDestroy();  
    81.     }  
    82.     /** 
    83.      * Setting Up Bluetooth 
    84.      */  
    85.     private void setBluetooth(){  
    86.          blueadapter=BluetoothAdapter.getDefaultAdapter();  
    87.            
    88.             if(blueadapter!=null){  //Device support Bluetooth  
    89.                 //确认开启蓝牙  
    90.                 if(!blueadapter.isEnabled()){  
    91.                     //请求用户开启  
    92.                     Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
    93.                     startActivityForResult(intent, RESULT_FIRST_USER);  
    94.                     //使蓝牙设备可见,方便配对  
    95.                     Intent in=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
    96.                     in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);  
    97.                     startActivity(in);  
    98.                     //直接开启,不经过提示  
    99.                     blueadapter.enable();  
    100.                 }  
    101.             }  
    102.             else{   //Device does not support Bluetooth  
    103.                   
    104.                 AlertDialog.Builder dialog = new AlertDialog.Builder(this);  
    105.                 dialog.setTitle("No bluetooth devices");  
    106.                 dialog.setMessage("Your equipment does not support bluetooth, please change device");  
    107.                   
    108.                 dialog.setNegativeButton("cancel",  
    109.                         new DialogInterface.OnClickListener() {  
    110.                             @Override  
    111.                             public void onClick(DialogInterface dialog, int which) {  
    112.                                   
    113.                             }  
    114.                         });  
    115.                 dialog.show();  
    116.             }  
    117.     }  
    118.       
    119.     /** 
    120.      * Finding Devices 
    121.      */  
    122.     private void findAvalibleDevice(){  
    123.         //获取可配对蓝牙设备  
    124.         Set<BluetoothDevice> device=blueadapter.getBondedDevices();  
    125.           
    126.         if(blueadapter!=null&&blueadapter.isDiscovering()){  
    127.             deviceList.clear();  
    128.             adapter.notifyDataSetChanged();  
    129.         }  
    130.         if(device.size()>0){ //存在已经配对过的蓝牙设备  
    131.             for(Iterator<BluetoothDevice> it=device.iterator();it.hasNext();){  
    132.                 BluetoothDevice btd=it.next();  
    133.                 deviceList.add(btd.getName()+' '+btd.getAddress());  
    134.                 adapter.notifyDataSetChanged();  
    135.             }  
    136.         }else{  //不存在已经配对过的蓝牙设备  
    137.             deviceList.add("No can be matched to use bluetooth");  
    138.             adapter.notifyDataSetChanged();  
    139.         }  
    140.     }  
    141.       
    142.     @Override  
    143.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    144.           
    145.         switch(resultCode){  
    146.         case RESULT_OK:  
    147.             findAvalibleDevice();  
    148.             break;  
    149.         case RESULT_CANCELED:  
    150.             break;  
    151.         }  
    152.         super.onActivityResult(requestCode, resultCode, data);  
    153.     }  
    154.   
    155.     private class ClinckMonitor implements OnClickListener{  
    156.   
    157.         @Override  
    158.         public void onClick(View v) {  
    159.             if(blueadapter.isDiscovering()){  
    160.                 blueadapter.cancelDiscovery();  
    161.                 btserch.setText("repeat search");  
    162.             }else{  
    163.                 findAvalibleDevice();  
    164.                 blueadapter.startDiscovery();  
    165.                 btserch.setText("stop search");  
    166.             }  
    167.         }  
    168.     }  
    169.     /** 
    170.      * 蓝牙搜索状态广播监听 
    171.      * @author Andy 
    172.      * 
    173.      */  
    174.     private class DeviceReceiver extends BroadcastReceiver{  
    175.   
    176.         @Override  
    177.         public void onReceive(Context context, Intent intent) {  
    178.             String action =intent.getAction();  
    179.             if(BluetoothDevice.ACTION_FOUND.equals(action)){    //搜索到新设备  
    180.                 BluetoothDevice btd=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
    181.                 //搜索没有配过对的蓝牙设备  
    182.                  if (btd.getBondState() != BluetoothDevice.BOND_BONDED) {  
    183.                      deviceList.add(btd.getName()+' '+btd.getAddress());  
    184.                      adapter.notifyDataSetChanged();  
    185.                  }  
    186.             }  
    187.              else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){   //搜索结束  
    188.                    
    189.                     if (deviceListview.getCount() == 0) {  
    190.                         deviceList.add("No can be matched to use bluetooth");  
    191.                         adapter.notifyDataSetChanged();  
    192.                     }  
    193.                     btserch.setText("repeat search");  
    194.                 }  
    195.         }     
    196.     }  
    197.   
    198.     @Override  
    199.     public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {  
    200.           
    201.         Log.e("msgParent""Parent= "+arg0);  
    202.         Log.e("msgView""View= "+arg1);  
    203.         Log.e("msgChildView""ChildView= "+arg0.getChildAt(pos-arg0.getFirstVisiblePosition()));  
    204.           
    205.             final String msg = deviceList.get(pos);  
    206.               
    207.             if(blueadapter!=null&&blueadapter.isDiscovering()){  
    208.                 blueadapter.cancelDiscovery();  
    209.                 btserch.setText("repeat search");  
    210.             }  
    211.               
    212.             AlertDialog.Builder dialog = new AlertDialog.Builder(this);// 定义一个弹出框对象  
    213.             dialog.setTitle("Confirmed connecting device");  
    214.             dialog.setMessage(msg);  
    215.             dialog.setPositiveButton("connect",  
    216.                     new DialogInterface.OnClickListener() {  
    217.                         @Override  
    218.                         public void onClick(DialogInterface dialog, int which) {  
    219.                             BluetoothMsg.BlueToothAddress=msg.substring(msg.length()-17);  
    220.                               
    221.                             if(BluetoothMsg.lastblueToothAddress!=BluetoothMsg.BlueToothAddress){  
    222.                                 BluetoothMsg.lastblueToothAddress=BluetoothMsg.BlueToothAddress;  
    223.                             }  
    224.                               
    225.                             Intent in=new Intent(SearchDeviceActivity.this,BluetoothActivity.class);  
    226.                             startActivity(in);  
    227.                           
    228.                         }  
    229.                     });  
    230.             dialog.setNegativeButton("cancel",  
    231.                     new DialogInterface.OnClickListener() {  
    232.                         @Override  
    233.                         public void onClick(DialogInterface dialog, int which) {  
    234.                             BluetoothMsg.BlueToothAddress = null;  
    235.                         }  
    236.                     });  
    237.             dialog.show();  
    238.     }  
    239.       
    240. }  

    BluetoothMsg.java

    [java] view plaincopy
    1. package com.hello.project;  
    2.   
    3. public class BluetoothMsg {  
    4.     /** 
    5.      * 蓝牙连接类型 
    6.      * @author Andy 
    7.      * 
    8.      */  
    9.     public enum ServerOrCilent{  
    10.         NONE,  
    11.         SERVICE,  
    12.         CILENT  
    13.     };  
    14.     //蓝牙连接方式  
    15.     public static ServerOrCilent serviceOrCilent = ServerOrCilent.NONE;  
    16.     //连接蓝牙地址  
    17.     public static String BlueToothAddress = null,lastblueToothAddress=null;  
    18.     //通信线程是否开启  
    19.     public static boolean isOpen = false;  
    20.           
    21. }  


    finddevice.xml

    [java] view plaincopy
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.    android:id = "@+id/devices"  
    4.     android:orientation="vertical"  
    5.     android:layout_width="fill_parent"  
    6.     android:layout_height="fill_parent"  
    7.     >  
    8.       
    9.     <RelativeLayout  
    10.       android:layout_width="fill_parent"  
    11.       android:layout_height="wrap_content"  
    12.       android:layout_alignParentBottom = "true"  
    13.       android:id= "@+id/bt_bottombar">       
    14.                       
    15.         <Button android:id="@+id/start_seach"  
    16.             android:layout_width="match_parent"   
    17.             android:layout_height="wrap_content"    
    18.             android:layout_toRightOf="@+id/start_service"  
    19.             android:text="Began to search"/>           
    20.     </RelativeLayout>    
    21.   
    22.      <ListView    
    23.         android:id="@+id/devicelist"  
    24.         android:layout_width="fill_parent"    
    25.         android:layout_height="fill_parent"   
    26.         android:scrollingCache="false"   
    27.         android:divider="#ffc6c6c6"   
    28.         android:layout_weight="1.0"   
    29.         android:layout_above = "@id/bt_bottombar"  
    30.         android:layout_below="@id/devices"  
    31.         />  
    32. </RelativeLayout>  


    BluetoothActivity.java

    [java] view plaincopy
    1. package com.hello.project;  
    2.   
    3. import java.io.IOException;  
    4. import java.io.InputStream;  
    5. import java.io.OutputStream;  
    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.BluetoothServerSocket;  
    14. import android.bluetooth.BluetoothSocket;  
    15. import android.content.Context;  
    16. import android.os.Bundle;  
    17. import android.os.Handler;  
    18. import android.os.Message;  
    19. import android.util.Log;  
    20. import android.view.View;  
    21. import android.view.View.OnClickListener;  
    22. import android.view.inputmethod.InputMethodManager;  
    23. import android.widget.AdapterView;  
    24. import android.widget.ArrayAdapter;  
    25. import android.widget.Button;  
    26. import android.widget.EditText;  
    27. import android.widget.ListView;  
    28. import android.widget.Toast;  
    29. import android.widget.AdapterView.OnItemClickListener;  
    30.   
    31. public class BluetoothActivity extends  Activity{  
    32.       
    33.     /* 一些常量。代表server的名称 */  
    34.     public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";  
    35.       
    36.     private ListView mListView;  
    37.     private Button sendButton;  
    38.     private Button disconnectButton;  
    39.     private EditText editMsgView;  
    40.     private ArrayAdapter<String> mAdapter;  
    41.     private List<String> msgList=new ArrayList<String>();  
    42.     Context mContext;  
    43.       
    44.     private BluetoothServerSocket mserverSocket = null;  
    45.     private ServerThread startServerThread = null;  
    46.     private clientThread clientConnectThread = null;  
    47.     private BluetoothSocket socket = null;  
    48.     private BluetoothDevice device = null;  
    49.     private readThread mreadThread = null;;   
    50.     private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
    51.       
    52.         @Override  
    53.         public void onCreate(Bundle savedInstanceState) {  
    54.             super.onCreate(savedInstanceState);   
    55.             setContentView(R.layout.chat);  
    56.             mContext = this;  
    57.             init();  
    58.         }  
    59.       
    60.         private void init() {            
    61.               
    62.             mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, msgList);  
    63.             mListView = (ListView) findViewById(R.id.list);  
    64.             mListView.setAdapter(mAdapter);  
    65.             mListView.setFastScrollEnabled(true);  
    66.             editMsgView= (EditText)findViewById(R.id.MessageText);    
    67.             editMsgView.clearFocus();  
    68.               
    69.             sendButton= (Button)findViewById(R.id.btn_msg_send);  
    70.             sendButton.setOnClickListener(new OnClickListener() {  
    71.                 @Override  
    72.                 public void onClick(View arg0) {  
    73.                   
    74.                     String msgText =editMsgView.getText().toString();  
    75.                     if (msgText.length()>0) {  
    76.                         sendMessageHandle(msgText);   
    77.                         editMsgView.setText("");  
    78.                         editMsgView.clearFocus();  
    79.                         //close InputMethodManager  
    80.                         InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);   
    81.                         imm.hideSoftInputFromWindow(editMsgView.getWindowToken(), 0);  
    82.                     }else  
    83.                     Toast.makeText(mContext, "发送内容不能为空!", Toast.LENGTH_SHORT).show();  
    84.                 }  
    85.             });  
    86.               
    87.             disconnectButton= (Button)findViewById(R.id.btn_disconnect);  
    88.             disconnectButton.setOnClickListener(new OnClickListener() {  
    89.                 @Override  
    90.                 public void onClick(View arg0) {  
    91.                     // TODO Auto-generated method stub  
    92.                     if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT)   
    93.                     {  
    94.                         shutdownClient();  
    95.                     }  
    96.                     else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE)   
    97.                     {  
    98.                         shutdownServer();  
    99.                     }  
    100.                     BluetoothMsg.isOpen = false;  
    101.                     BluetoothMsg.serviceOrCilent=BluetoothMsg.ServerOrCilent.NONE;  
    102.                     Toast.makeText(mContext, "已断开连接。", Toast.LENGTH_SHORT).show();  
    103.                 }  
    104.             });       
    105.         }      
    106.   
    107.         private Handler LinkDetectedHandler = new Handler() {  
    108.             @Override  
    109.             public void handleMessage(Message msg) {  
    110.                 //Toast.makeText(mContext, (String)msg.obj, Toast.LENGTH_SHORT).show();  
    111.                 if(msg.what==1)  
    112.                 {  
    113.                     msgList.add((String)msg.obj);  
    114.                 }  
    115.                 else  
    116.                 {  
    117.                     msgList.add((String)msg.obj);  
    118.                 }  
    119.                 mAdapter.notifyDataSetChanged();  
    120.                 mListView.setSelection(msgList.size() - 1);  
    121.             }  
    122.         };      
    123.           
    124.     @Override  
    125.     protected void onResume() {  
    126.           
    127.         BluetoothMsg.serviceOrCilent=BluetoothMsg.ServerOrCilent.CILENT;  
    128.           
    129.          if(BluetoothMsg.isOpen)  
    130.             {  
    131.                 Toast.makeText(mContext, "连接已经打开。能够通信。假设要再建立连接,请先断开!

      ", Toast.LENGTH_SHORT).show();  

    132.                 return;  
    133.             }  
    134.             if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.CILENT)  
    135.             {  
    136.                 String address = BluetoothMsg.BlueToothAddress;  
    137.                 if(!address.equals("null"))  
    138.                 {  
    139.                     device = mBluetoothAdapter.getRemoteDevice(address);      
    140.                     clientConnectThread = new clientThread();  
    141.                     clientConnectThread.start();  
    142.                     BluetoothMsg.isOpen = true;  
    143.                 }  
    144.                 else  
    145.                 {  
    146.                     Toast.makeText(mContext, "address is null !", Toast.LENGTH_SHORT).show();  
    147.                 }  
    148.             }  
    149.             else if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.SERVICE)  
    150.             {                     
    151.                 startServerThread = new ServerThread();  
    152.                 startServerThread.start();  
    153.                 BluetoothMsg.isOpen = true;  
    154.             }  
    155.         super.onResume();  
    156.     }  
    157.   
    158.     //开启client  
    159.         private class clientThread extends Thread {           
    160.             @Override  
    161.             public void run() {  
    162.                 try {  
    163.                     //创建一个Socket连接:仅仅须要server在注冊时的UUID号  
    164.                     // socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);  
    165.                     socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
    166.                     //连接  
    167.                     Message msg2 = new Message();  
    168.                     msg2.obj = "请稍候。正在连接server:"+BluetoothMsg.BlueToothAddress;  
    169.                     msg2.what = 0;  
    170.                     LinkDetectedHandler.sendMessage(msg2);  
    171.                       
    172.                     socket.connect();  
    173.                       
    174.                     Message msg = new Message();  
    175.                     msg.obj = "已经连接上服务端。能够发送信息。";  
    176.                     msg.what = 0;  
    177.                     LinkDetectedHandler.sendMessage(msg);  
    178.                     //启动接受数据  
    179.                     mreadThread = new readThread();  
    180.                     mreadThread.start();  
    181.                 }   
    182.                 catch (IOException e)   
    183.                 {  
    184.                     Log.e("connect""", e);  
    185.                     Message msg = new Message();  
    186.                     msg.obj = "连接服务端异常!断开连接又一次试一试。";  
    187.                     msg.what = 0;  
    188.                     LinkDetectedHandler.sendMessage(msg);  
    189.                 }   
    190.             }  
    191.         };  
    192.   
    193.         //开启server  
    194.         private class ServerThread extends Thread {   
    195.             @Override  
    196.             public void run() {  
    197.                           
    198.                 try {  
    199.                     /* 创建一个蓝牙server  
    200.                      * 參数分别:server名称、UUID   */   
    201.                     mserverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,  
    202.                             UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));         
    203.                       
    204.                     Log.d("server""wait cilent connect...");  
    205.                       
    206.                     Message msg = new Message();  
    207.                     msg.obj = "请稍候。正在等待client的连接...";  
    208.                     msg.what = 0;  
    209.                     LinkDetectedHandler.sendMessage(msg);  
    210.                       
    211.                     /* 接受client的连接请求 */  
    212.                     socket = mserverSocket.accept();  
    213.                     Log.d("server""accept success !");  
    214.                       
    215.                     Message msg2 = new Message();  
    216.                     String info = "client已经连接上!能够发送信息。";  
    217.                     msg2.obj = info;  
    218.                     msg.what = 0;  
    219.                     LinkDetectedHandler.sendMessage(msg2);  
    220.                     //启动接受数据  
    221.                     mreadThread = new readThread();  
    222.                     mreadThread.start();  
    223.                 } catch (IOException e) {  
    224.                     e.printStackTrace();  
    225.                 }  
    226.             }  
    227.         };  
    228.         /* 停止server */  
    229.         private void shutdownServer() {  
    230.             new Thread() {  
    231.                 @Override  
    232.                 public void run() {  
    233.                     if(startServerThread != null)  
    234.                     {  
    235.                         startServerThread.interrupt();  
    236.                         startServerThread = null;  
    237.                     }  
    238.                     if(mreadThread != null)  
    239.                     {  
    240.                         mreadThread.interrupt();  
    241.                         mreadThread = null;  
    242.                     }                 
    243.                     try {                     
    244.                         if(socket != null)  
    245.                         {  
    246.                             socket.close();  
    247.                             socket = null;  
    248.                         }  
    249.                         if (mserverSocket != null)  
    250.                         {  
    251.                             mserverSocket.close();/* 关闭服务器 */  
    252.                             mserverSocket = null;  
    253.                         }  
    254.                     } catch (IOException e) {  
    255.                         Log.e("server""mserverSocket.close()", e);  
    256.                     }  
    257.                 };  
    258.             }.start();  
    259.         }  
    260.         /* 停止client连接 */  
    261.         private void shutdownClient() {  
    262.             new Thread() {  
    263.                 @Override  
    264.                 public void run() {  
    265.                     if(clientConnectThread!=null)  
    266.                     {  
    267.                         clientConnectThread.interrupt();  
    268.                         clientConnectThread= null;  
    269.                     }  
    270.                     if(mreadThread != null)  
    271.                     {  
    272.                         mreadThread.interrupt();  
    273.                         mreadThread = null;  
    274.                     }  
    275.                     if (socket != null) {  
    276.                         try {  
    277.                             socket.close();  
    278.                         } catch (IOException e) {  
    279.                             // TODO Auto-generated catch block  
    280.                             e.printStackTrace();  
    281.                         }  
    282.                         socket = null;  
    283.                     }  
    284.                 };  
    285.             }.start();  
    286.         }  
    287.           
    288.         //发送数据  
    289.         private void sendMessageHandle(String msg)   
    290.         {         
    291.             if (socket == null)   
    292.             {  
    293.                 Toast.makeText(mContext, "没有连接", Toast.LENGTH_SHORT).show();  
    294.                 return;  
    295.             }  
    296.             try {                 
    297.                 OutputStream os = socket.getOutputStream();   
    298.                 os.write(msg.getBytes());  
    299.             } catch (IOException e) {  
    300.                 e.printStackTrace();  
    301.             }             
    302.             msgList.add(msg);  
    303.             mAdapter.notifyDataSetChanged();  
    304.             mListView.setSelection(msgList.size() - 1);  
    305.         }  
    306.         //读取数据  
    307.         private class readThread extends Thread {   
    308.             @Override  
    309.             public void run() {  
    310.                   
    311.                 byte[] buffer = new byte[1024];  
    312.                 int bytes;  
    313.                 InputStream mmInStream = null;  
    314.                   
    315.                 try {  
    316.                     mmInStream = socket.getInputStream();  
    317.                 } catch (IOException e1) {  
    318.                     // TODO Auto-generated catch block  
    319.                     e1.printStackTrace();  
    320.                 }     
    321.                 while (true) {  
    322.                     try {  
    323.                         // Read from the InputStream  
    324.                         if( (bytes = mmInStream.read(buffer)) > 0 )  
    325.                         {  
    326.                             byte[] buf_data = new byte[bytes];  
    327.                             for(int i=0; i<bytes; i++)  
    328.                             {  
    329.                                 buf_data[i] = buffer[i];  
    330.                             }  
    331.                             String s = new String(buf_data);  
    332.                             Message msg = new Message();  
    333.                             msg.obj = s;  
    334.                             msg.what = 1;  
    335.                             LinkDetectedHandler.sendMessage(msg);  
    336.                         }  
    337.                     } catch (IOException e) {  
    338.                         try {  
    339.                             mmInStream.close();  
    340.                         } catch (IOException e1) {  
    341.                             // TODO Auto-generated catch block  
    342.                             e1.printStackTrace();  
    343.                         }  
    344.                         break;  
    345.                     }  
    346.                 }  
    347.             }  
    348.         }  
    349.         @Override  
    350.         protected void onDestroy() {  
    351.             super.onDestroy();  
    352.   
    353.             if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT)   
    354.             {  
    355.                 shutdownClient();  
    356.             }  
    357.             else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE)   
    358.             {  
    359.                 shutdownServer();  
    360.             }  
    361.             BluetoothMsg.isOpen = false;  
    362.             BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.NONE;  
    363.         }  
    364.   
    365.           
    366. }  

    chat.xml

    [java] view plaincopy
    1. <?xml version="1.0" encoding="utf-8"?

      >  

    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.    android:id = "@+id/container"  
    4.     android:orientation="vertical"  
    5.     android:layout_width="fill_parent"  
    6.     android:layout_height="fill_parent"  
    7.     >  
    8.       
    9.     <RelativeLayout  
    10.       android:layout_width="fill_parent"  
    11.       android:layout_height="wrap_content"  
    12.       android:id= "@+id/edit_bottombar"  
    13.       android:layout_alignParentBottom = "true">  
    14.   
    15.         <Button android:id="@+id/btn_disconnect"  
    16.             android:layout_width="65dp"   
    17.             android:layout_height="wrap_content"    
    18.             android:layout_alignParentLeft ="true"  
    19.             android:text="断开"/>   
    20.               
    21.         <Button android:id="@+id/btn_msg_send"  
    22.             android:layout_width="65dp"   
    23.             android:layout_height="wrap_content"    
    24.             android:layout_alignParentRight ="true"  
    25.             android:text="发送"/>    
    26.         <EditText  
    27.              android:layout_width="fill_parent"  
    28.              android:layout_height = "wrap_content"  
    29.              android:layout_toLeftOf="@id/btn_msg_send"  
    30.              android:layout_toRightOf="@+id/btn_disconnect"                
    31.              android:hint = "说点什么呢?"  
    32.              android:textSize="15dip"  
    33.              android:id = "@+id/MessageText"/>  
    34.     </RelativeLayout>    
    35.   
    36.      <ListView    
    37.         android:id="@+id/list"  
    38.         android:layout_width="fill_parent"    
    39.         android:layout_height="fill_parent"   
    40.         android:scrollingCache="false"   
    41.         android:divider="#ffc6c6c6"   
    42.         android:layout_weight="1.0"   
    43.         android:layout_above = "@id/edit_bottombar"  
    44.         android:layout_below="@id/container"  
    45.         />  
    46. </RelativeLayout>  


    最后别忘了增加权限

    [java] view plaincopy
    1. <uses-permission android:name="android.permission.BLUETOOTH"/>  
    2.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  
    3.     <uses-permission android:name="android.permission.READ_CONTACTS"/>  

    扩展:蓝牙后台配对实现(网上看到的整理例如以下)

    [java] view plaincopy
    1. static public boolean createBond(Class btClass, BluetoothDevice btDevice)  
    2.             throws Exception {  
    3.         Method createBondMethod = btClass.getMethod("createBond");  
    4.         Log.i("life""createBondMethod = " + createBondMethod.getName());  
    5.         Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
    6.         return returnValue.booleanValue();  
    7.     }  
    8.   
    9.     static public boolean setPin(Class btClass, BluetoothDevice btDevice,  
    10.             String str) throws Exception {  
    11.         Boolean returnValue = null;  
    12.         try {  
    13.             Method removeBondMethod = btClass.getDeclaredMethod("setPin",  
    14.                     new Class[] { byte[].class });  
    15.             returnValue = (Boolean) removeBondMethod.invoke(btDevice,  
    16.                     new Object[] { str.getBytes() });  
    17.             Log.i("life""returnValue = " + returnValue);  
    18.         } catch (SecurityException e) {  
    19.             // throw new RuntimeException(e.getMessage());  
    20.             e.printStackTrace();  
    21.         } catch (IllegalArgumentException e) {  
    22.             // throw new RuntimeException(e.getMessage());  
    23.             e.printStackTrace();  
    24.         } catch (Exception e) {  
    25.             // TODO Auto-generated catch block  
    26.             e.printStackTrace();  
    27.         }  
    28.         return returnValue;  
    29.     }  
    30.   
    31.     // 取消用户输入  
    32.     static public boolean cancelPairingUserInput(Class btClass,  
    33.             BluetoothDevice device) throws Exception {  
    34.         Method createBondMethod = btClass.getMethod("cancelPairingUserInput");  
    35.         // cancelBondProcess()  
    36.         Boolean returnValue = (Boolean) createBondMethod.invoke(device);  
    37.         Log.i("life""cancelPairingUserInputreturnValue = " + returnValue);  
    38.         return returnValue.booleanValue();  
    39.     }  


    然后监听蓝牙配对的广播  匹配“android.bluetooth.device.action.PAIRING_REQUEST”这个action
    然后调用上面的setPin(mDevice.getClass(), mDevice, "1234"); // 手机和蓝牙採集器配对
    createBond(mDevice.getClass(), mDevice);
    cancelPairingUserInput(mDevice.getClass(), mDevice);
    mDevice是你要去连接的那个蓝牙的对象 , 1234为配对的pin码



  • 相关阅读:
    docker容器升级脚本
    Haproxy状态监控配置教程
    负载均衡之Haproxy配置详解(及httpd配置)
    升级代码脚本
    升级数据库脚本(加入事务)
    监控端口,新疆模拟用户登录脚本
    mongodb3.2系统性学习——3、update()操作
    Java Socket编程
    php错误级别设置
    php 用于绘图使用的颜色数组
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/6814575.html
Copyright © 2011-2022 走看看