安卓手机APP和HC05蓝牙模块通信.docx
《安卓手机APP和HC05蓝牙模块通信.docx》由会员分享,可在线阅读,更多相关《安卓手机APP和HC05蓝牙模块通信.docx(12页珍藏版)》请在冰豆网上搜索。
安卓手机APP和HC05蓝牙模块通信
androidandbuletoothHC-05connect
//authorEngineer-Tang,Itaketwomonth finish thisprogram,itvreyuseful;Iamsohappy;
//welcomegivemoreadvise,critical.
packagecom.internet.bluetooth_4;
importjava.io.IOException;
importBusinessBluetooth.BusinessBluetooth;
importBusinessBluetooth.BusinessBluetooth.OnportListener;
importandroid.app.Activity;
importandroid.content.Context;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.TextView;
importandroid.widget.Toast;
publicclassMainActivityextendsActivityimplementsOnClickListener,OnportListener{
EditTextedtMessage;
Buttonbtnsend;
privateTextViewtvresult;
BusinessBluetoothm_BusinessBluethooth;
privateContextmContext;
privateHandlerHandler=newHandler(){
publicvoidhandleMessage(android.os.Messagemsg){
switch(msg.what){
case0x0001:
Stringindex=(String)msg.obj;
tvresult.setText("接收的数据"+index);
break;
}
};
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitView();
InitListener();
m_BusinessBluethooth=newBusinessBluetooth(this);
m_BusinessBluethooth.CreatePortLinsten();
}
privatevoidInitView(){
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnsend=(Button)findViewById(R.id.btnSend);
}
privatevoidInitListener(){
btnsend.setOnClickListener(this);
tvresult=(TextView)findViewById(R.id.tvresult);
}
@Override
publicvoidonClick(Viewv){
switch(v.getId()){
caseR.id.btnSend:
newThread(){
publicvoidrun(){
Messagemsg=newMessage();
msg.what=0x0001;
msg.obj=m_BusinessBluethooth.add2;
Handler.sendMessage(msg);
};
}.start();
break;
}
}
@Override
protectedvoidonDestroy(){
super.onDestroy();
if(m_BusinessBluethooth.mmSocket!
=null){
//关闭连接
try{
m_BusinessBluethooth.mmSocket.close();
}catch(IOExceptione){
}
}
}
publicvoidOnReceiveData(Stringp_Message){
Log.i("BusinessBluetooth11","接收的数据+"+p_Message);
}
}
/**
*
*/
/**
*@authortanggong,Itaketwomonth finishthisprogram,itvreyuseful;Iamsohappy;
*
*/
packageBusinessBluetooth;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.Set;
importjava.util.UUID;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.bluetooth.BluetoothServerSocket;
importandroid.bluetooth.BluetoothSocket;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.util.Log;
importandroid.widget.Toast;
publicclassBusinessBluetooth{
//publicfinalBluetoothSocketmmSocket;
privatestaticfinalStrings_tag="BusinessBlue";
privateBluetoothAdapterm_BluetoothAdapter;
privateContextm_Context;
privateConnectThreadm_ConnectThread;
privateBluetoothDevice_device=null;//蓝牙设备
privateMessagem_Message=newMessage();
publicOnportListenerm_OnportListener;
publicStringadd1,add2;
privateAcceptThreadmAcceptThread;
public BluetoothSocketmmSocket;
privateConnectedThreadmConnectedThread;
private BluetoothSocketpm;
privateHandlerm_Handler=newHandler(){
//给一些提示信息,这个作用不大
publicvoidhandleMessage(android.os.Messagemsg){
switch(msg.what){
case1:
Toast.makeText(m_Context,"蓝牙设备不存在或关闭,请打开后重启服务器",Toast.LENGTH_LONG).show();
break;
}
};
};
privatestaticfinalStrings_Name="98:
D3:
31:
FB:
31:
D5";
privatestaticfinalUUIDs_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//实现一个接口
publicinterfaceOnportListener{
publicabstractvoidOnReceiveData(Stringp_Message);
}
publicBusinessBluetooth(Contextp_Context){
m_Context=p_Context;
m_Message.what=1;
m_OnportListener=(OnportListener)p_Context;
}
//启动和蓝牙,因为我是手机先接好蓝牙模块后再通信的。
publicvoidCreatePortLinsten(){
try{
m_BluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(m_BluetoothAdapter!
=null){
if(!
m_BluetoothAdapter.isEnabled()){
}
_device=m_BluetoothAdapter.getRemoteDevice(s_Name);
m_ConnectThread=new ConnectThread(_device);
m_ConnectThread.start();
SetpairedDevices=m_BluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0){
//Loopthroughpaireddevices
for(BluetoothDevicedevice:
pairedDevices){
// if(device.getAddress().contentEquals(s_Name)){
// m_ConnectThread=new ConnectThread(device);
// m_ConnectThread.start();
//break;
// }
}
}
if(mAcceptThread==null)
{
mAcceptThread=newAcceptThread();
mAcceptThread.start();
}
mConnectedThread=new ConnectedThread(pm);
mConnectedThread.start();
}else{
m_Handler.sendMessage(m_Message);
}
}catch(Exceptione){
Log.i(s_tag,"CreatePortListen:
"+e.getMessage());
CreatePortLinsten();
}
}
//服务端接口线程
publicclassAcceptThreadextendsThread{
privatefinalBluetoothServerSocketmmServerSocket;
publicAcceptThread(){
BluetoothServerSockettmp=null;
try{
tmp=m_BluetoothAdapter.listenUsingRfcommWithServiceRecord(s_Name,s_UUID);
}catch(Exceptione){}
mmServerSocket=tmp;
}
publicvoidrun(){
BluetoothSocketsocket=null;
while(true){
try{
socket=mmServerSocket.accept();
}catch(Exceptione){
}
if(socket!
=null){
mConnectedThread=new ConnectedThread(pm);
mConnectedThread.start();
try{
mmServerSocket.close();
}catch(IOExceptione){
e.printStackTrace();
}
cancel();
break;
}
}
}
/**Willcancelthelisteningsocket,andcausethethreadtofinish*/
publicvoidcancel(){
try{
mmServerSocket.close();
}catch(Exceptione){}
}
}
//客服端接口线程连接
privateclassConnectThreadextendsThread{
//privatefinalBluetoothSocketmmSocket;
privatefinal BluetoothDevicemmDevice;
publicConnectThread(BluetoothDevicedevice){
BluetoothSockettmp=null;
mmDevice=device;
try{
tmp=mmDevice.createRfcommSocketToServiceRecord(s_UUID);
}catch(Exceptione){}
mmSocket=tmp;
}
publicvoidrun(){
try{
mmSocket.connect();
pm=mmSocket;
mConnectedThread=new ConnectedThread(pm);
mConnectedThread.start();
}catch(ExceptionconnectException){
try{
mmSocket.close();
}catch(ExceptioncloseException){}
cancel();
return;
}
}
/**Willcancelanin-progressconnection,andclosethesocket*/
publicvoidcancel(){
try{
mmSocket.close();
}catch(Exceptione){}
}
}
//传输数据
privateclassConnectedThreadextendsThread{
privatefinalBluetoothSocketmmSocket;
privatefinalInputStreammmInStream;
privatefinalOutputStreammmOutStream;
publicConnectedThread(BluetoothSocketsocket){
mmSocket=socket;
InputStreamtmpIn=null;
OutputStreamtmpOut=null;
//Gettheinputandoutputstreams,usingtempobjectsbecause
//memberstreamsarefinal
try{
//add1="d";
tmpIn=socket.getInputStream();
tmpOut=socket.getOutputStream();
// add1="e";
}catch(Exceptione){}
mmInStream=tmpIn;
mmOutStream=tmpOut;
}
publicvoidrun(){
byte[]buffer=newbyte[30]; //bufferstoreforthestream
intbytes;//bytesreturnedfromread()
while(true){
try{
add2=newString(buffer);
bytes=mmInStream.read(buffer);
add2=add2+newString(buffer);
}catch(Exceptione){
break;
}
}
}
//下面这二个没用到,目前只收没发
publicvoidwrite(byte[]bytes){
try{
mmOutStream.write(bytes);
}catch(Exceptione){}
}
publicvoidcancel(){
try{
mmSocket.close();
}catch(Exceptione){}
}
}
}