Learning Android - Bluetooth communication

Bluetooth
Bluetooth is a radio technology support (usually within 10m, and no barrier media) short-range communication device. Wireless information can be exchanged between mobile phone, PDA, wireless headsets, laptop computers and other equipment included. The use of "Bluetooth" technology, can effectively simplify the communication between the mobile communication terminal device, communication can be successfully simplified, so that the data transmission between the device and the Internet more quickly and efficiently, to widen the road for wireless communications.

Note: Android 2.0 introduced a Bluetooth interface, in the development, need real test, if required data transmission, also need two machines, additional hardware support Bluetooth under yo.

Bluetooth devices operate
permissions:

<-permission uses Android: name = "android.permission.BLUETOOTH_ADMIN" />
<-permission uses Android: name = "android.permission.BLUETOOTH" />
There are two ways to open the Bluetooth:

// The first method, turn on the Bluetooth device (prompt dialog box)
the Intent = new new discoverableIntent the Intent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity (discoverableIntent);
// second method, open Bluetooth, silent open
BluetoothAdapter BluetoothAdapter = BluetoothAdapter.getDefaultAdapter ();
bluetoothAdapter.enable ();
search for Bluetooth devices

// start scanning Bluetooth devices
BluetoothAdapter bluetoothAdapter2 BluetoothAdapter.getDefaultAdapter = ();
bluetoothAdapter2.startDiscovery ();
Close Bluetooth

= BluetoothAdapter.getDefaultAdapter bluetoothAdapter1 BluetoothAdapter ();
bluetoothAdapter1.disable ();
 
Bluetooth communication Case

 

 

 


 

MainActivity.java

package com.example.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button open, close,button_scan,button_server,button_client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = findViewById(R.id.open);
close = findViewById(R.id.close);
button_scan = findViewById(R.id.button_scan);
button_server = (Button) findViewById(R.id.button_server);
button_client = (Button) findViewById(R.id.button_client);
open.setOnClickListener(this);
close.setOnClickListener(this);
button_scan.setOnClickListener(this);
button_server.setOnClickListener(this);
button_client.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.open:
/*//第一种方法,打开蓝牙设备(提示对话框)
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//打开本机蓝牙发现功能
discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity (discoverableIntent); * /

// second method, turn on Bluetooth muting open
BluetoothAdapter BluetoothAdapter BluetoothAdapter.getDefaultAdapter = ();
bluetoothAdapter.enable ();
BREAK;
Case R. id.close:
BluetoothAdapter bluetoothAdapter1 BluetoothAdapter.getDefaultAdapter = ();
bluetoothAdapter1.disable ();
BREAK;
Case R.id.button_scan:
// start scan for Bluetooth devices
BluetoothAdapter bluetoothAdapter2 BluetoothAdapter.getDefaultAdapter = ();
bluetoothAdapter2.startDiscovery ();
the Log .i ( "tag", "start scanning Bluetooth devices");
the Set <BluetoothDevice> SET = bluetoothAdapter2.getBondedDevices ();
for (BluetoothDevice BD: SET) {
Log.i("tag","name:"+bd.getName());
Log.i("tag","address:"+bd.getAddress());
}
break;
case R.id.button_server:
Intent intent = new Intent(this, ServerBluetoothActivity.class);
startActivity(intent);
break;
case R.id.button_client:
Intent intent1 = new Intent(this, ClientBluetoothActivity.class);
startActivity(intent1);
break;
default:
break;
}
}
}
ServerBluetoothActivity.java

package com.example.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.util.UUID;

public class ServerBluetoothActivity extends AppCompatActivity {

private static final int CONN_SUCCESS=0x1;
private static final int CONN_FAIL=0x2;
private static final int RECEIVER_INFO=0x3;
private static final int SET_EDITTEXT_NULL=0x4;
private static Button button_send;
private static TextView textView_content;
private static EditText editText_info;
BluetoothAdapter bluetoothAdapter=null;//本地蓝牙设备
BluetoothServerSocket serverSocket=null;//蓝牙设备Socket服务端
BluetoothSocket socket=null;//蓝牙设备Socket客户端

//输入输出流
PrintStream out;
BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
the setContentView (R.layout.activity_server_bluetooth);
setTitle ( "Bluetooth server");
textView_content = (the TextView) the findViewById (R.id.textView_content);
editText_info = (the EditText) the findViewById (R.id. editText_info);
button_send = (the Button) findViewById (R.id.button_send);
the init ();
}

// create a Bluetooth server of the Socket
Private void the init () {
textView_content.setText ( "server is up, waiting for connection ... \ n-");
new new the Thread (the Runnable new new () {
@Override
public void RUN () {
// get the local device. 1.
BluetoothAdapter BluetoothAdapter.getDefaultAdapter = ();
. 2 // create Bluetooth Socket server
try {
= bluetoothAdapter.listenUsingRfcommWithServiceRecord serverSocket ( "text", UUID.fromString ( "00000000-2527-eef3-ffffe3160865-FFFF"));
.. 3 // blocked waiting client requests Socket
Socket serverSocket.accept = ();
IF (Socket! null =) {
OUT = new new PrintStream (Socket.getOutputStream ());
in the BufferedReader new new = (the InputStreamReader new new (Socket.getInputStream ()));
}
handler.sendEmptyMessage (CONN_SUCCESS);
} the catch (IOException E) {
e.printStackTrace ();
the Message MSG = handler.obtainMessage (CONN_FAIL, e.getLocalizedMessage ());
handler.sendMessage (MSG);
}
}
.}) Start ();
}

// memory leak preventing proper use
private final MyHandler handler = new MyHandler (this);
public class MyHandler extends Handler {
//软引用
WeakReference<ServerBluetoothActivity> weakReference;

public MyHandler(ServerBluetoothActivity activity) {
weakReference=new WeakReference<ServerBluetoothActivity>(activity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ServerBluetoothActivity activity=weakReference.get();
if (activity!=null){
switch (msg.what){
case RECEIVER_INFO:
setInfo(msg.obj.toString()+"\n");
break;
case SET_EDITTEXT_NULL:
editText_info.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功!\n");
button_send.setEnabled (true);
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败!\n");
setInfo(msg.obj.toString() + "\n");
break;
default:
break;
}
}
}
}
private boolean isReceiver=true;

private class ReceiverInfoThread implements Runnable {
@Override
public void run() {
String info=null;
while (isReceiver){
try {
info=in.readLine();
Message msg=handler.obtainMessage(RECEIVER_INFO,info);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public void sendClick(View view){
final String content=editText_info.getText().toString();
if (TextUtils.isEmpty(content)){
Toast.makeText(this, "不能发送空消息", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
handler.sendEmptyMessage(SET_EDITTEXT_NULL);
}
}).start();
}
private void setInfo(String info){
StringBuffer sb=new StringBuffer();
sb.append(textView_content.getText());
sb.append(info);
textView_content.setText(sb);
}
}
ClientBluetoothActivity.java

package com.example.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.util.UUID;

public class ClientBluetoothActivity extends AppCompatActivity {
private static final int CONN_SUCCESS=0x1;
private static final int CONN_FAIL=0x2;
private static final int RECEIVER_INFO=0x3;
private static final int SET_EDITTEXT_NULL=0x4;
private static Button button_send;
private static TextView textView_content;
private static EditText editText_info;

BluetoothAdapter bluetooth=null;//本地蓝牙设备
BluetoothDevice device=null;//远程蓝牙设备
BluetoothSocket socket=null;//蓝牙设备Socket客户端

//输入输出流
PrintStream out;
BufferedReader in;
@Override
void the onCreate protected (the Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
the setContentView (R.layout.activity_client_bluetooth);

setTitle ( "Bluetooth client");
textView_content = (the TextView) the findViewById (R.id.textView_content);
editText_info = ( the EditText) findViewById (R.id.editText_info);
button_send = (the Button) findViewById (R.id.button_send);
the init ();
}

// create Bluetooth client side of the Socket
Private void the init () {
textView_content.setText ( "customer end has started, waiting for connection ... \ n-");
new new the Thread (the Runnable new new () {
@Override
public void RUN () {
// get the default adapter. 1 local Bluetooth device.
Bluetooth BluetoothAdapter.getDefaultAdapter = ();
// 2. get a remote Bluetooth device via local Bluetooth device
= bluetooth.getRemoteDevice Device ( "22 is: 22 is: 4E: 6E: 59: 86");
// create and return a BoluetoothSocket. 3 in accordance with the UUID.
the try {
Socket = device.createRfcommSocketToServiceRecord (UUID.fromString ( "00000000-2527-eef3 ffffe3160865--ffff "));
IF (Socket = null) {!
// connected
Socket.connect ();
// process the client output stream
OUT = new new PrintStream (Socket.getOutputStream ());
in the BufferedReader new new = (new new the InputStreamReader (Socket.getInputStream ()));
}
handler.sendEmptyMessage (CONN_SUCCESS);
} the catch (IOException E) {
e.printStackTrace ();
the Message MSG = handler.obtainMessage (CONN_FAIL, e.getLocalizedMessage ());
handler.sendMessage (MSG);
}
}
.}) Start ();
}
//防止内存泄漏 正确的使用方法
private final MyHandler handler = new MyHandler(this);
public class MyHandler extends Handler {
//软引用
WeakReference<ClientBluetoothActivity> weakReference;

public MyHandler(ClientBluetoothActivity activity) {
weakReference = new WeakReference<ClientBluetoothActivity>(activity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ClientBluetoothActivity activity = weakReference.get();
if (activity!=null){
switch (msg.what){
case RECEIVER_INFO:
setInfo(msg.obj.toString() + "\n");
break;
case SET_EDITTEXT_NULL:
editText_info.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功!\n");
button_send.setEnabled(true);
System.out.println("name"+device.getName());
System.out.println("Uuids"+device.getUuids());
System.out.println("Address"+device.getAddress());
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败!\n");
setInfo(msg.obj.toString() + "\n");
break;
default:
break;
}
}
}
}
private boolean isReceiver=true;
//接收信息的线程
class ReceiverInfoThread implements Runnable{
@Override
public void run() {
String info=null;
while (isReceiver){
try {
Log.i("tag","--ReceiverInfoThread start --");
info=in.readLine();
Log.i("tag","--ReceiverInfoThread read --");
Message msg=handler.obtainMessage(RECEIVER_INFO,info);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public void sendClick(View v){
final String content=editText_info.getText().toString();
if (TextUtils.isEmpty(content)){
Toast.makeText(this, "不能发送空消息", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
handler.sendEmptyMessage(SET_EDITTEXT_NULL);
}
}).start();
}
private void setInfo(String info){
StringBuffer sb=new StringBuffer();
sb.append(textView_content.getText());
sb.append(info);
textView_content.setText(sb);
}

--------------------- 

Guess you like

Origin www.cnblogs.com/hyhy904/p/10995876.html
Recommended