AndroidBLE与终端通信(四)——实现服务器与客户端即时通讯功能在开始之前,别忘了添加权限uses-permissionandroid:name=android.permission.BLUETOOTH/uses-permissionandroid:name=android.permission.BLUETOOTH_ADMIN/一.OpenBluetoothGoogle的API上说的是十分的清楚,我们作为初学者要把他当做说明书一样来看待这样的话,我们就来实现打开蓝牙并且打开可见性,可见性默认是120s,MAX为3600s,这里在强调一遍,打开蓝牙有两种方式,一种是弹框提示,一种是强制打开,这在之前也是提过好多次了的/***打开蓝牙并且搜索*/publicvoidopenBluetooth(Viewv){//开启搜索IntentdiscoverableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//设置可见性300sdiscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);startActivity(discoverableIntent);//强制打开//mBluetoothAdapter.enable();}CloseBluetooth关闭蓝牙也就直接调用BluetoothAdapter的disable()方法;/***关闭蓝牙*/publicvoidcloseBluetooth(Viewv){mBluetoothAdapter.disable();}客户端我们在MainActivity中写一个button直接跳转到ClientActivity中去/***打开客户端*/publicvoidClient(Viewv){startActivity(newIntent(this,ClientActivity.class));}ClientActivitypackagecom.example.ble_qq;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.SocketOptions;importjava.util.UUID;importcom.example.ble_qq.ServiceActivity.ReceiverInfoThread;importandroid.app.Activity;importandroid.bluetooth.BluetoothAdapter;importandroid.bluetooth.BluetoothDevice;importandroid.bluetooth.BluetoothServerSocket;importandroid.bluetooth.BluetoothSocket;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.text.TextUtils;importandroid.util.Log;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.TextView;importandroid.widget.Toast;/***客户端**@authorLGL**/publicclassClientActivityextendsActivity{//连接成功privatestaticfinalintCONN_SUCCESS=0x1;//连接失败privatestaticfinalintCONN_FAIL=0x2;privatestaticfinalintRECEIVER_INFO=0x3;//设置文本框为空privatestaticfinalintSET_EDITTEXT_NULL=0x4;//接收到的消息privateTextViewtv_content;//输入框privateEditTextet_info;//发送按钮privateButtonbtn_send;//本地蓝牙适配器privateBluetoothAdaptermBluetoothAdapter=null;//远程设备privateBluetoothDevicedevice=null;//蓝牙设备Socket客户端privateBluetoothSocketsocket=null;privatebooleanisReceiver=true;//设备名称privatestaticfinalStringNAME=LGL;//输入输出流privatePrintStreamout;privateBufferedReaderin;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){//TODOAuto-generatedmethodstubsuper.onCreate(savedInstanceState);setTitle(客户端);setContentView(R.layout.activity_client);initView();//初始化Socket客户端连接init();}privatevoidinitView(){//初始化tv_content=(TextView)findViewById(R.id.tv_content);et_info=(EditText)findViewById(R.id.et_info);btn_send=(Button)findViewById(R.id.btn_send);}privatevoidinit(){tv_content.setText(客户端已经启动,正在与服务端连接...\n);//开始连接newThread(newRunnable(){@Overridepublicvoidrun(){try{//得到本地蓝牙适配器mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();//通过本地适配器得到地址,这个地址可以公共扫描来获取,就是getAddress()返回的地址device=mBluetoothAdapter.getRemoteDevice(98:6C:F5:CE:0E:81);//根据UUID返回一个socket,要与服务器的UUID一致socket=device.createRfcommSocketToServiceRecord(UUID.fromString(00000000-2527-eef3-ffff-ffffe3160865));if(socket!=null){//连接socket.connect();//处理流out=newPrintStream(socket.getOutputStream());in=newBufferedReader(newInputStreamReader(socket.getInputStream()));}//连接成功发送handlerhandler.sendEmptyMessage(CONN_SUCCESS);}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();Messagemes=handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());handler.sendMessage(mes);}}}).start();}/***Handler接收消息**/privateHandlerhandler=newHandler(){publicvoidhandleMessage(Messagemsg){switch(msg.what){caseCONN_SUCCESS:setInfo(连接成功!\n);btn_send.setEnabled(true);Log.i(设备的名称,device.getName());Log.i(设备的UUID,device.getUuids()+);Log.i(设备的地址,device.getAddress());//开始接收信息newThread(newReceiverInfoThread()).start();break;caseCONN_FAIL:setInfo(连接失败!\n);setInfo(msg.obj.toString()+\n);break;caseRECEIVER_INFO:setInfo(msg.obj.toString()+\n);break;caseSET_EDITTEXT_NULL:et_info.setText();break;}}};/***接收消息的线程*/classReceiverInfoThreadimplementsRunnable{@Overridepublicvoidrun(){Stringinfo=null;while(isReceiver){try{info=in.readLine();Messagemsg=handler.obtainMessage(RECEIVER_INFO);handler.sendMessage(msg);}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}}/***发送消息*/publicvoidSendText(Viewv){finalStringtext=et_info.getText().toString();//不能为空if(!TextUtils.isEmpty(text)){Toast.makeText(this,不能为空,Toast.LENGTH_SHORT).show();}newThread(newRunnable(){@Overridepublicvoidrun(){//输出out.println(text);out.flush();//把文本框设置为空handler.sendEmptyMessage(SET_EDITTEXT_NULL);}}).start();}/***拼接文本信息*/privatevoidsetInfo(Stringinfo){StringBuffersb=newStringBuffer();sb.append(tv_content.getText());sb.append(info);tv_content.setText(sb);}}服务端我们在MainActivity中写一个button直接跳转到ServiceActivity中去/***打开服务端*/publicvoidService(Viewv){startActivity(newIntent(this,ServiceActivity.class));}ServiceActivitypackagecom.example.ble_qq;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.util.UUID;importandroid.app.Activity;importandroid.bluetooth.Bluet