蓝牙介绍:
是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换
添加权限
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
打开蓝牙并设置允许被搜索
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//开启蓝牙
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//允许蓝牙被搜索
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//设置允许被搜索时间200s内可以被搜索到
startActivity(intent);
关闭蓝牙
adapter.disable();
搜索附近的蓝牙
adapter.startDiscovery();
点击扫描到的设备进行配对蓝牙
device.createBond();
获得已经配对的蓝牙设备
adapter.getBondedDevices()
使用蓝牙传输数据:socket和ServerSocket传输数据
//1.获得客户端Socket
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
//2.获得服务端Socket
BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getName(),uuid);
serverSocket.accpet();
BluetoothManager 蓝牙管理类,管理BluetoothAdapter。主要负责管理蓝牙的本地连接。
BluetoothAdapter 蓝牙适配器类:代表本蓝牙设备
BluetoothDevice 蓝牙设备,配对后的远程蓝牙设备.
BluetoothServiceSocket 服务端连接类
BluetoothSocket:客户端连接类
UUID(universal unique identifier , 全局唯一标识符)
文件传输服务:00001106-0000-1000-8000-00805F9B34FB
开启蓝牙、关闭蓝牙、显示列表、点击配对
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/start_BlueTooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="开启蓝牙"/>
<Button
android:id="@+id/close_BlueTooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="关闭蓝牙"/>
<Button
android:id="@+id/search_BlueTooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="搜索设备"/>
<ListView
android:id="@+id/name_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></ListView>
</LinearLayout>
Activity
public class MainActivity extends AppCompatActivity{
private ListView nameList;
private BluetoothAdapter adapter;
private MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameList = (ListView) findViewById(R.id.name_list);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void initMyBlueTooth() {
BluetoothManager manager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter = manager.getAdapter();//获得自己的蓝牙
}
private void init() {
String[] strings = new String[]{
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_FINE_LOCATION
};
if (Build.VERSION.SDK_INT>Build.VERSION_CODES.M) {//判断版本
//判断是不是已经授权
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(strings,101);
}
}
initMyBlueTooth();
myReceiver = new MyReceiver(nameList);
//注册广播接受者
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);//注册搜索蓝牙的广播
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//结束搜索
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态的改变
registerReceiver(myReceiver,filter);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_BlueTooth:
open();
break;
case R.id.close_BlueTooth:
close();
break;
case R.id.search_BlueTooth:
search();
break;
}
}
private void search() {
adapter.startDiscovery();//搜索设备
}
private void close() {
adapter.disable();//关闭蓝牙
}
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,300);//设置被搜索的时长
startActivity(intent);
}
}
MyReceiver
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "MyReceiver";
private List<BluetoothDevice> data=new ArrayList<>();
private ListView listView;
private BluetoothDevice device2;
public MyReceiver(ListView listView) {
this.listView = listView;
}
@Override
public void onReceive(Context context, Intent intent) {
//其他蓝牙
MyAdapter adapter = new MyAdapter(context, data);
listView.setAdapter(adapter);
if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
data.add(device);
adapter.notifyDataSetChanged();
}else if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
//将所有蓝牙显示到界面上
}else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
device2=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int state=device2.getBondState();
switch (state) {
case BluetoothDevice.BOND_BONDED:
Log.i(TAG, "onReceive: -----------------连接成功");
//发送文件
new ClientThread().start();
break;
}
}
//设置列表点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//点击连接
data.get(i).createBond();
}
});
}
}
Adapter
public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<BluetoothDevice> data;
public MyAdapter(Context context, List<BluetoothDevice> data) {
mContext = context;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int i) {
return data.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view==null) {
view= LayoutInflater.from(mContext).inflate(R.layout.layout_blue_tooth,null);
viewHolder=new ViewHolder();
viewHolder.textView=view.findViewById(R.id.bluetooth_name);
view.setTag(viewHolder);
}else {
viewHolder= (ViewHolder) view.getTag();
}
viewHolder.textView.setText(data.get(i).getName());
return view;
}
class ViewHolder{
TextView textView;
}
}