当前位置: 移动技术网 > 移动技术>移动开发>Android > Android蓝牙上位机实现发送指令与接收信息功能的方法

Android蓝牙上位机实现发送指令与接收信息功能的方法

2018年09月14日  | 移动技术网移动技术  | 我要评论

现市面上的蓝牙模块基本都相同,开发者只需要下载本文源程序,然后按如下注释处,更改发送指令的内容就可以了。

//发送按键响应
 public void onsendbuttonclicked(view v){
 	try{
 		outputstream os = _socket.getoutputstream();//蓝牙连接输出流
 		byte[] bos = {0x53,0x4e,0x06,0x00,0x04,0x05,0x00,0x00,0x0f};  //花括号内是要发送的指令,根据需要更改,这里是我随便输入的
 		os.write(bos);	
 	}catch(ioexception e){  		
 	}  	
 }

下面是接收数据线程,接收数据转换为16进制数的字符串进行显示,在注释的代码部分,若要修改数据显示的编码方式,在此处。

//接收数据线程  
thread readthread=new thread(){  
      
    public void run(){  
        int num = 0;  
        byte[] buffer = new byte[1024];  
        byte[] buffer_new = new byte[1024];  
        int i = 0;  
        int n = 0;  
        brun = true;  
        //接收线程  
        while(true){  
            try{  
                while(is.available()==0){  
                    while(brun == false){}  
                }  
                while(true){  
                    num = is.read(buffer);         //读入数据  
                    n=0;  
                    for(i=0;i<num;i++){  
                        if((buffer[i] == 0x0d)&&(buffer[i+1]==0x0a)){  
                            buffer_new[n] = 0x0a;  
                            i++;  
                        }else{  
                            buffer_new[n] = buffer[i];  
                        }  
                        n++;  
                    }  
                    string s = "";      
                    for (int i = 0; i < bos.length; i++)   
                    {  
                        string hex = integer.tohexstring(bos[i] & 0xff);  
                        if (hex.length() == 1)   
                        {  
                            hex = '0' + hex;  
                        }  
                        s += hex.touppercase()+" ";       
                    }            //  for循环和integer.tohexstring()方法实现byte数组转换成16进制字符串  
                    smsg+=s;   //写入接收缓存  
                    if(is.available()==0)break;  //短时间没有数据才跳出进行显示  
                }  
                //发送显示消息,进行显示刷新  
                    handler.sendmessage(handler.obtainmessage());                         
                }catch(ioexception e){  
                }  
        }  
    }  
}  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网