安卓学习-蓝牙通讯

image

image

image

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xiaofei.app.bluetooth.MainActivity">


<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开蓝牙设备"
android:id="@+id/open"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭蓝牙设备"
android:id="@+id/close"
android:layout_below="@+id/open"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="搜索蓝牙设备"
android:id="@+id/button_scan"
android:layout_below="@+id/close"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
package com.xiaofei.app.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Set;

public class MainActivity extends Activity implements View.OnClickListener {
private Button open, close,button_scan;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = (Button) findViewById(R.id.open);
close = (Button) findViewById(R.id.close);
button_scan = (Button) findViewById(R.id.button_scan);
open.setOnClickListener(this);
close.setOnClickListener(this);
button_scan.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);*/

//第二种方法,打开蓝牙,静默打开
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
break;
case R.id.close:
BluetoothAdapter bluetoothAdapter1=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter1.disable();
break;
case R.id.button_scan:
//开始扫描蓝牙设备
BluetoothAdapter bluetoothAdapter2=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter2.startDiscovery();
System.out.println("开始扫描蓝牙设备");
Set<BluetoothDevice> set=bluetoothAdapter2.getBondedDevices();
for (BluetoothDevice bd : set)
{
System.out.println("name"+bd.getName());
System.out.println("address"+bd.getAddress());

}
break;
default:
break;

}
}
}

image

image

image

image

image

等…………………..

imageimageimage

MainActivity.java

package com.xiaofei.app.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Set;

public class MainActivity extends Activity 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 = (Button) findViewById(R.id.open);
close = (Button) findViewById(R.id.close);
button_scan = (Button) 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);*/

//第二种方法,打开蓝牙,静默打开
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
break;
case R.id.close:
BluetoothAdapter bluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter1.disable();
break;
case R.id.button_scan:
//开始扫描蓝牙设备
BluetoothAdapter bluetoothAdapter2 = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter2.startDiscovery();
System.out.println("开始扫描蓝牙设备");
Set<BluetoothDevice> set = bluetoothAdapter2.getBondedDevices();
for (BluetoothDevice bd : set) {
System.out.println("name" + bd.getName());
System.out.println("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.xiaofei.app.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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 Activity {
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;//本地蓝牙设备
BluetoothServerSocket serverSocket=null;//蓝牙设备Socket服务端
BluetoothSocket socket=null;//蓝牙设备Socket客户端

//输入输出流
PrintStream out;
BufferedReader in;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_bluetooth);
setTitle("蓝牙服务端");
textView_content= (TextView) findViewById(R.id.textView_content);
editText_info= (EditText) findViewById(R.id.editText_info);
button_send= (Button) findViewById(R.id.button_send);
init();
}
//创建蓝牙服务器端的Socket
private void init() {
textView_content.setText("服务器已启动,正在等待连接...\n");
new Thread(new Runnable() {
@Override
public void run() {
//1.得到本地设备
bluetooth=BluetoothAdapter.getDefaultAdapter();
//2.创建蓝牙Socket服务器
try
{
serverSocket=bluetooth.listenUsingRfcommWithServiceRecord("text", UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
//3.阻塞等待Socket客户端请求
socket=serverSocket.accept();
if (socket!=null)
{
out=new PrintStream(socket.getOutputStream());
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
handler.sendEmptyMessage(CONN_SUCCESS);
}
catch (IOException e)
{
e.printStackTrace();
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<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;
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 v)
{
final String content=editText_info.getText().toString();
if (TextUtils.isEmpty(content))
{
Toast.makeText(ServerBluetoothActivity.this,"不能发送空消息",Toast.LENGTH_LONG).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.xiaofei.app.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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 ClientBluetoothActivity extends Activity {
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_bluetooth);
setTitle("蓝牙客户端");
textView_content= (TextView) findViewById(R.id.textView_content);
editText_info= (EditText) findViewById(R.id.editText_info);
button_send= (Button) findViewById(R.id.button_send);
init();
}
//创建蓝牙客户端端的Socket
private void init() {
textView_content.setText("客户端已启动,正在等待连接...\n");
new Thread(new Runnable() {
@Override
public void run() {
//1.得到本地蓝牙设备的默认适配器
bluetooth=BluetoothAdapter.getDefaultAdapter();
//2.通过本地蓝牙设备得到远程蓝牙设备
device=bluetooth.getRemoteDevice("22:22:4E:6E:59:86");
//3.根据UUID创建并返回一个BoluetoothSocket
try {
socket=device.createRfcommSocketToServiceRecord(UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
if (socket!=null)
{
// 连接
socket.connect();
//处理客户端输出流
out=new PrintStream(socket.getOutputStream());
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

}
handler.sendEmptyMessage(CONN_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
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 {
System.out.println("--ReceiverInfoThread start --");
info=in.readLine();
System.out.println("--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(ClientBluetoothActivity.this,"不能发送空消息",Toast.LENGTH_LONG).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);
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xiaofei.app.bluetooth.MainActivity">


<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开蓝牙设备"
android:id="@+id/open"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭蓝牙设备"
android:id="@+id/close"
android:layout_below="@+id/open"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="搜索蓝牙设备"
android:id="@+id/button_scan"
android:layout_below="@+id/close"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="服务器端"
android:id="@+id/button_server"
android:layout_below="@+id/button_scan"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/button_scan"
android:layout_alignEnd="@+id/button_scan" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="客户端"
android:id="@+id/button_client"
android:layout_below="@+id/button_server"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/button_server"
android:layout_alignEnd="@+id/button_server" />
</RelativeLayout>

activity_client_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xiaofei.app.bluetooth.ServerBluetoothActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:id="@+id/textView_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/editText_info"
android:layout_below="@+id/textView" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_info"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/button_send"
android:layout_toStartOf="@+id/button_send" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:id="@+id/button_send"
android:onClick="sendClick"
android:layout_alignBottom="@+id/editText_info"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="客户端"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

activity_server_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xiaofei.app.bluetooth.ServerBluetoothActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:id="@+id/textView_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/editText_info"
android:layout_below="@+id/textView" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText_info"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/button_send"
android:layout_toStartOf="@+id/button_send" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:id="@+id/button_send"
android:onClick="sendClick"
android:layout_alignBottom="@+id/editText_info"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="服务器端"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

转载于:https://my.oschina.net/xiaofeiandroid/blog/668197

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值