Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android設備終端與藍牙模塊(HC-06)的通訊編程思路

android設備終端與藍牙模塊(HC-06)的通訊編程思路

編輯:關於Android編程

藍牙模塊(HC-06):

vcC20cDEo7/pyc+ho7b4vdPK3MC20cDEo7/pt6K5/cC0tcTQxc+itcTKsbryo6zKx8O709Cx2NKq1Nm0tL2ot/7O8cb3tsu1xKOsztLDx9a70qrSu7j2sru2z7zgzP221Le9z/vPorXE0a27t77N0NChozwvcD4KPHA+IDwvcD4KPHA+16LS4qO61Npzb2NrZXQuY29ubmVjdCgpo7vWrsewo6zO0sPH0OjSqta00NBibHVldG9vdGhhZGFwdGVyLmNhbmNlbGRpc2NvdmVyeSgpO6Os1eLKx86qwcvNo7X0y9HL98nosbijrLfx1PLBrL3Tv8nE3LvhseS1w7fHs6PC/aOssqLH0sjd0tfKp7DcoaM8L3A+CjxwPiA8L3A+CjxwPsC20cC/qrei1tC1xLy4uPa52Lz8sr3W6KO6PC9wPgo8cD4xoaK/qsb0yta7+snPtcTAttHAuabE3KGjPC9wPgo8cD4yoaLL0cv3uL29/LTm1Nq1xMC20cDJ6LG4oaM8L3A+CjxwPjOhorS0vajAttHAc29ja2V0o6zTyXNvY2tldLvxyKFkZXZpY2WhozwvcD4KPHA+NKGit6LLzbrNtsHIocr9vt2hozwvcD4KPHA+NaGix+WzoaOots+/qrj31tbP37PMo6zXos/6ueOypb3TytXG97XIo6k8L3A+CjxwPiA8L3A+CjxwPi8v1vfP38z1PC9wPgo8cD5BZGFwdGVyICAtLS0tPiAgIGRldmljZSAgLS0tLS0+ICBzb2NrZXQ8L3A+CjxwPiA8L3A+Cgo8cD4vKiBzdGVwMTrIobXDxKzIz7XEwLbRwMrKxeTG9yAqLzwvcD4KPHByZSBjbGFzcz0="brush:java;">private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

//step2:強制開啟藍牙設備

if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}


//step3:注冊廣播接收器,注意:開啟step4即搜索設備前,應先注冊廣播接收器

reg_broadcastreceiver();
 
private void reg_broadcastreceiver(){
 //Register for broadcasts when a device is discovered
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, discoveryFilter);
        //System.out.println("***********" + mBtAddress);
        //Register for broadcasts when discovery has finished
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, foundFilter);
}
 
  
    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                
            	Log.d("BroadcastReceiver", "find device:"+device.getName()+"|"+device.getAddress());
                mBtAddress = device.getAddress();  
                                
        	 //step5:根據搜索到的藍牙設備的MAC地址,得到該設備
        	 mBtDevice = mBtAdapter.getRemoteDevice(mBtAddress);
        	 //step6:開啟客戶端線程,線程裡面完成了與SPP協議的連接 
        	 mBtClientConnectThread = new clientThread();
        	 mBtClientConnectThread.start();
        
        
           
            }  // When discovery is finished, change the Activity title
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
            {
               setTitle("搜索完成");
               
               Log.d("BroadcastReceiver", "find over");
            }
          
           
        }
    };
 


//step4: 開始搜索附近可以存在的藍牙設備,之後系統會發送廣播給廣播接收器

mBtAdapter.startDiscovery();


//附加客戶端線程 代碼

 //客戶端線程 
	private class clientThread extends Thread{
		public void run(){
			Log.d("mBtSocket", "start-->"+mBtSocket);
			try {
//step7,取消搜索設備的動作,否則接下來的設備連接會失敗
				mBtAdapter.cancelDiscovery();
//step8,根據device獲取socket
				mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//step9,連接socket
				mBtSocket.connect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e("connect", "", e);
				Log.d("clientThread", "連接失敗");
				
			}
			Log.d("mBtSocket", "end-->"+mBtSocket);
		}
	}



//step10,發送數據.

sendMessageHandle(“要發送的數據”);

//step10, 讀取數據

(由於接收數據的線程已經打開,所以當有數據到來時,數據就自動賦給變量S了,而此時S就是我們讀取的數據 )


//step11,清場(清場動作放在ondestroy裡面)

@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		//關閉客戶端進程,取消廣播接收器
    	shutdownClient();
        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
        //關閉讀線程 
		if(mReadThread != null)
		{
			mReadThread.interrupt();
			mReadThread = null;
		}				
	}


/* 停止客戶端連接 */
	private void shutdownClient() {
		new Thread() {
			public void run() {
				if(mBtClientConnectThread!=null)
				{
					mBtClientConnectThread.interrupt();
					mBtClientConnectThread= null;
				}
				if (mBtSocket != null) {
					try {
						mBtSocket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mBtSocket = null;
				}
			};
		}.start();
	}



	//發送數據
	public static void sendMessageHandle(String msg) 
	{		
		if (mBtSocket == null)  
		{
			Log.d("----------------------", "沒有連接");
			return;
		}
		
		try {
			OutputStream os = mBtSocket.getOutputStream(); 
			os.write(msg.getBytes()); //發送出去的值為:msg
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}




附:發送數據和讀取數據的代碼
//發送數據
	public static void sendMessageHandle(String msg) 
	{		
		if (mBtSocket == null)  
		{
			Log.d("----------------------", "沒有連接");
			return;
		}
		
		try {
			OutputStream os = mBtSocket.getOutputStream(); 
			os.write(msg.getBytes()); //發送出去的值為:msg
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}
	
	//讀取數據
    private static class readThread extends Thread { 
        public void run() {
        	
            byte[] buffer = new byte[1024];
            int bytes;
            InputStream mmInStream = null;
            
			try {
				mmInStream = mBtSocket.getInputStream();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
            while (true) {
                try {
                    // Read from the InputStream
                    if( (bytes = mmInStream.read(buffer)) > 0 )
                    {
	                    byte[] buf_data = new byte[bytes];
				    	for(int i=0; i

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved