package com.example.bluetooth;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
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.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* android 连接 蓝牙 (配置)
*/
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
// 拿到 BluetoothAdapter
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> deviceListAdapter;
private ListView deviceListView;
private BluetoothDevice selectedDevice;
private BluetoothSocket bluetoothSocket;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
createBluetoothBond();
registerBroadcast();
}
// 初始化
private void init() {
// 获取蓝牙配置器 BluetoothAdapter 方式1.
BluetoothManager bluetoothManger =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManger.getAdapter();
//方式2
// bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
// 蓝牙配对
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("MissingPermission")
private void createBluetoothBond() {
if (bluetoothAdapter == null) {
Toast.makeText(this, "没有蓝牙功能", Toast.LENGTH_SHORT).show();
return;
}
if (!bluetoothAdapter.isEnabled()) {
// 没有开启蓝牙 开启蓝牙
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//判断是否有访问位置的权限,没有权限,直接申请位置权限
if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
// 创建设备列表适配器
deviceListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
deviceListView = (ListView) findViewById(R.id.device_list);
deviceListView.setAdapter(deviceListAdapter);
deviceListView.setOnItemClickListener((adapterView, view, i, l) -> {
//当点击某个蓝牙列表时,需要停止扫描,减少性能的消耗
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
String deviceName = deviceListAdapter.getItem(i);
Log.e("nyz", "deviceName " + deviceName);
selectedDevice = bluetoothAdapter.getRemoteDevice(deviceName.split("\\n")[1]);
Log.e("nyz", "name " + selectedDevice.getName());
Log.e("nyz", "address " + selectedDevice.getAddress());
ParcelUuid[] uuids = selectedDevice.getUuids();
for (int index = 0; index < uuids.length; index++) {
Log.e("nyz", "uuids " + uuids[index]);
}
//开始链接
connectToDevice(selectedDevice);
});
// 搜索设备按钮点击事件
Button searchButton = (Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(view -> {
startDeviceDiscovery();
});
findViewById(R.id.search_button1).setOnClickListener(v -> {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
});
}
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("MissingPermission")
private void startDeviceDiscovery() {
deviceListAdapter.clear();
int state = bluetoothAdapter.getState();
Log.e("nyz", "state " + state);
boolean b = bluetoothAdapter.startDiscovery();
Log.e("nyz", "bluetooth state " + b);
//获取已经连接过的设备。
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
Log.e("nyz", "device " + device.getName());
deviceListAdapter.add(device.getName() + "\n" + device.getAddress());
deviceListAdapter.notifyDataSetChanged();
}
}
@SuppressLint("MissingPermission")
private void connectToDevice(BluetoothDevice device) {
new Thread() {
@Override
public void run() {
super.run();
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // SPP UUID for serial communication
try {
// 进行配对
if (!(device.getBondState() == BluetoothDevice.BOND_BONDED)) {
Log.e("nyz", "等待配对");
boolean success = device.createBond();
Log.e("nyz", "配对结果 " + success);
} else {
Log.e("nyz", "已经配对过");
}
// 等待配对完成
// Thread.sleep(500);
Log.e("nyz", "创建 socket");
bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
Log.e("nyz", "connect...");
if (bluetoothSocket == null) {
Log.e("nyz", "connect...failed");
return;
} else {
Log.e("nyz", "socket 创建成功");
}
new Thread() {
@Override
public void run() {
super.run();
try {
bluetoothSocket.connect();
// 成功连接
Log.e("nyz", "链接成功...");
InputStream inputStream = bluetoothSocket.getInputStream();
OutputStream outputStream = bluetoothSocket.getOutputStream();
Log.e("nyz", "inputStream " + (inputStream != null));
Log.e("nyz", "outputStream " + (outputStream != null));
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
Log.e("nyz", "conn failed");
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
BlueTooth,Android 蓝牙设备扫描,链接,通信 (112个子文件)
gradlew.bat 3KB
executionHistory.bin 640KB
fileHashes.bin 67KB
outputFiles.bin 21KB
resourceHashesCache.bin 20KB
last-build.bin 1B
.gitignore 225B
.gitignore 50B
.gitignore 6B
build.gradle 1021B
settings.gradle 464B
build.gradle 161B
gradlew 6KB
bluetooth.app.iml 9KB
bluetooth.iml 917B
gradle-wrapper.jar 58KB
MainActivity.java 16KB
ExampleInstrumentedTest.java 756B
ExampleUnitTest.java 382B
buildOutputCleanup.lock 17B
checksums.lock 17B
executionHistory.lock 17B
dependencies-accessors.lock 17B
fileHashes.lock 17B
proguard-rules.pro 750B
gradle.properties 1KB
local.properties 457B
gradle-wrapper.properties 236B
cache.properties 51B
gc.properties 0B
gc.properties 0B
gc.properties 0B
ic_launcher_round.webp 8KB
ic_launcher_round.webp 6KB
ic_launcher_round.webp 4KB
ic_launcher.webp 4KB
ic_launcher_round.webp 3KB
ic_launcher.webp 3KB
ic_launcher.webp 2KB
ic_launcher_round.webp 2KB
ic_launcher.webp 1KB
ic_launcher.webp 982B
workspace.xml 6KB
ic_launcher_background.xml 5KB
AndroidManifest.xml 2KB
ic_launcher_foreground.xml 2KB
Gradle__androidx_test_espresso_espresso_idling_resource_3_4_0_aar.xml 1KB
Gradle__androidx_coordinatorlayout_coordinatorlayout_1_1_0_aar.xml 1KB
Gradle__androidx_test_espresso_espresso_core_3_4_0_aar.xml 1KB
Gradle__androidx_viewpager2_viewpager2_1_0_0_aar.xml 1KB
Gradle__androidx_recyclerview_recyclerview_1_1_0_aar.xml 1KB
Gradle__androidx_drawerlayout_drawerlayout_1_0_0_aar.xml 1KB
Gradle__androidx_activity_activity_1_2_3_aar.xml 1KB
Gradle__com_google_android_material_material_1_4_0_aar.xml 1015B
Gradle__androidx_transition_transition_1_2_0_aar.xml 1013B
Gradle__androidx_test_ext_junit_1_1_3_aar.xml 1005B
Gradle__androidx_appcompat_appcompat_1_3_0_aar.xml 1004B
Gradle__androidx_fragment_fragment_1_3_4_aar.xml 995B
Gradle__androidx_test_core_1_4_0_aar.xml 985B
Gradle__androidx_test_monitor_1_4_0_aar.xml 981B
Gradle__androidx_test_runner_1_4_0_aar.xml 974B
Gradle__androidx_lifecycle_lifecycle_viewmodel_savedstate_2_3_1_aar.xml 971B
Gradle__androidx_print_print_1_0_0_aar.xml 968B
Gradle__androidx_core_core_1_5_0_aar.xml 959B
Gradle__androidx_annotation_annotation_experimental_1_0_0_aar.xml 931B
Gradle__androidx_localbroadcastmanager_localbroadcastmanager_1_0_0_aar.xml 913B
Gradle__androidx_vectordrawable_vectordrawable_animated_1_1_0_aar.xml 912B
Gradle__androidx_legacy_legacy_support_core_utils_1_0_0_aar.xml 908B
Gradle__androidx_appcompat_appcompat_resources_1_3_0_aar.xml 905B
Gradle__androidx_lifecycle_lifecycle_livedata_core_2_3_1_aar.xml 902B
Gradle__androidx_versionedparcelable_versionedparcelable_1_1_1_aar.xml 898B
Gradle__androidx_lifecycle_lifecycle_viewmodel_2_3_1_aar.xml 877B
Gradle__androidx_dynamicanimation_dynamicanimation_1_0_0_aar.xml 874B
Gradle__androidx_lifecycle_lifecycle_livedata_2_0_0_aar.xml 872B
Gradle__androidx_lifecycle_lifecycle_runtime_2_3_1_aar.xml 866B
Gradle__androidx_vectordrawable_vectordrawable_1_1_0_aar.xml 858B
Gradle__androidx_savedstate_savedstate_1_1_0_aar.xml 852B
Gradle__androidx_cursoradapter_cursoradapter_1_0_0_aar.xml 850B
Gradle__androidx_documentfile_documentfile_1_0_0_aar.xml 842B
Gradle__androidx_interpolator_interpolator_1_0_0_aar.xml 842B
Gradle__androidx_test_services_storage_1_4_0_aar.xml 841B
Gradle__androidx_arch_core_core_runtime_2_1_0_aar.xml 836B
Gradle__androidx_arch_core_core_runtime_2_0_0_aar.xml 836B
themes.xml 831B
themes.xml 831B
Gradle__androidx_customview_customview_1_0_0_aar.xml 826B
Gradle__androidx_viewpager_viewpager_1_0_0_aar.xml 818B
Gradle__androidx_cardview_cardview_1_0_0_aar.xml 810B
Gradle__androidx_loader_loader_1_0_0_aar.xml 794B
Gradle__org_hamcrest_hamcrest_integration_1_3.xml 789B
gradle.xml 765B
Gradle__org_hamcrest_hamcrest_library_1_3.xml 760B
activity_main.xml 755B
Gradle__org_hamcrest_hamcrest_core_1_3.xml 740B
Gradle__com_squareup_javawriter_2_1_1.xml 733B
Gradle__javax_inject_javax_inject_1.xml 719B
Gradle__junit_junit_4_13_2.xml 677B
Gradle__junit_junit_4_12.xml 663B
misc.xml 660B
Gradle__androidx_constraintlayout_constraintlayout_2_0_4_aar.xml 658B
共 112 条
- 1
- 2
资源评论
niuyongzhi
- 粉丝: 6
- 资源: 14
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- HM2305B-VB一款P-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明
- 基于52单片机、ADC0832、LCD1602、两个74HC393和一个74HC08的频率测量计 不能用,请私我
- HM2302-VB一款N-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明
- python实战项目-学生成绩管理系统(基础版)
- 微信小程序源码 实现查公交 滴滴公交 app 源码下载
- HM2302E-VB一款N-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明
- 基于C#图片相似度比较,感知哈希算法
- VR开发的概要介绍与分析
- 自动驾驶定位系列教程七:点云畸变补偿.pdf
- HM2302D-VB一款N-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功