##客户端
权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
1.开启蓝牙
private void open() {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
startActivityForResult(intent,105);
}
2.关闭蓝牙
bluetoothAdapter.disable();
3.扫描蓝牙
开始扫描 配合广播扫描
bluetoothAdapter.startDiscovery();
广播中 添加集合
class MyRecevier extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list_discover.add(device);
discoveryAdapter.notifyDataSetChanged();
}
}
}
注册广播
myRecevier = new MyRecevier();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(myRecevier,intentFilter);
4、显示已配对设备
//已经配对的蓝牙的集合
private void bond() {
Set<BluetoothDevice> bondDevices = bluetoothAdapter.getBondedDevices();
list_bond.clear();
list_bond.addAll(bondDevices);
bondAdapter.notifyDataSetChanged();
}
5.向已配对设备 发送数据
BluetoothDevice device = list_bond.get(p);
//建立链接 链接后发送数据
try {
//创建BluetoothSocket
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
//调用connect建立链接
socket.connect();
//判断是否连接成功
if (socket.isConnected()) {
socket.getOutputStream().write("http://www.yangdog.com/uploads/allimg/180525/09530W018-0.jpg".getBytes());//发送
//接收结果
// InputStream inputStream = socket.getInputStream();
// byte[] bytes = new byte[1024];
// int len = 0;
// String s = new String(bytes,0,len);
// Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "链接失败", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
package com.example.day06_bluetooth;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.day06_bluetooth.adapter.BondAdapter;
import com.example.day06_bluetooth.adapter.DiscoveryAdapter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//蓝牙通讯规范
private Button start1;
private Button close1;
private Button saomiao;
private RecyclerView showTooth;
private Button already;
private RecyclerView showAlready;
//扫描
private List<BluetoothDevice> list_discover = new ArrayList<>();
private DiscoveryAdapter discoveryAdapter;
private MyRecevier myRecevier;
//配对
private List<BluetoothDevice> list_bond= new ArrayList<>();
private BondAdapter bondAdapter;
private BluetoothAdapter bluetoothAdapter;
private BluetoothManager bluetoothManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
},110);
}
initView();
initBlueTooth();
initRecevier();
}
private void initRecevier() {
myRecevier = new MyRecevier();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(myRecevier,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myRecevier);
}
private void initBlueTooth() {
bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
}
private void initView() {
start1 = (Button) findViewById(R.id.start1);
close1 = (Button) findViewById(R.id.close1);
saomiao = (Button) findViewById(R.id.saomiao);
showTooth = (RecyclerView) findViewById(R.id.show_tooth);
already = (Button) findViewById(R.id.already_);
showAlready = (RecyclerView) findViewById(R.id.show_already);
start1.setOnClickListener(this);
close1.setOnClickListener(this);
saomiao.setOnClickListener(this);
already.setOnClickListener(this);
discoveryAdapter = new DiscoveryAdapter(list_discover,this);
showTooth.setAdapter(discoveryAdapter);
showTooth.setLayoutManager(new LinearLayoutManager(this));
// 点击配对
discoveryAdapter.setMyClickListener(new MyClickListener() {
@Override
public void MyItemOnclickListener(int p) {
BluetoothDevice device = list_discover.get(p);
device.createBond();
}
});
bondAdapter = new BondAdapter(list_bond,this);
showAlready.setAdapter(bondAdapter);
showAlready.setLayoutManager(new LinearLayoutManager(this));
//向已配对设备发送数据
bondAdapter.setMyClickListener(new MyClickListener() {
@Override
public void MyItemOnclickListener(int p) {
BluetoothDevice device = list_bond.get(p);
//建立链接 链接后发送数据
try {
//创建BluetoothSocket
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
//调用connect建立链接
socket.connect();
//判断是否连接成功
if (socket.isConnected()) {
socket.getOutputStream().write("http://www.yangdog.com/uploads/allimg/180525/09530W018-0.jpg".getBytes());//发送
//接收结果
// InputStream inputStream = socket.getInputStream();
// byte[] bytes = new byte[1024];
// int len = 0;
// String s = new String(bytes,0,len);
// Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "链接失败", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start1:
open();
break;
case R.id.close1:
close();
break;
case R.id.saomiao:
discovery();
break;
case R.id.already_:
bond();
break;
}
}
//已经配对的蓝牙的集合
private void bond() {
Set<BluetoothDevice> bondDevices = bluetoothAdapter.getBondedDevices();
list_bond.clear();
list_bond.addAll(bondDevices);
bondAdapter.notifyDataSetChanged();
}
//扫描
private void discovery() {
bluetoothAdapter.startDiscovery();
}
private void close() {
bluetoothAdapter.disable();
Toast.makeText(this, "关闭蓝牙", Toast.LENGTH_SHORT).show();
}
private void open() {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
startActivityForResult(intent,105);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(this, "打开蓝牙", Toast.LENGTH_SHORT).show();
}
class MyRecevier extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list_discover.add(device);
discoveryAdapter.notifyDataSetChanged();
}
}
}
}
package com.example.day06_bluetooth_service;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//蓝牙通讯规范
private Button staSer;
private ImageView img;
private BluetoothAdapter bluetoothAdapter;
private BluetoothManager bluetoothManager;
private Handler handler = new Handler();
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
},110);
}
staSer = (Button) findViewById(R.id.sta_ser);
img = (ImageView) findViewById(R.id.img_);
tv = (TextView) findViewById(R.id.tv);
bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
staSer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//BlueToothServerSocket---->blueToothAdapter
BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
//调用accpet方法接受客户端的链接-->BluetoothSocket
BluetoothSocket socket = serverSocket.accept();//阻塞方法
//接受数据
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
final String s = new String(bytes, 0, len);
handler.post(new Runnable() {
@Override
public void run() {
tv.setText(s);
Glide.with(MainActivity.this).load("http://www.yangdog.com/uploads/allimg/180525/09530W018-0.jpg").into(img);
Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}