一、引言
- 描述:藍(lán)牙技術(shù)是一種無(wú)線數(shù)據(jù)和語(yǔ)音通信開(kāi)放的全球規(guī)范,它是基于低成本的近距離無(wú)線連接,為固定和移動(dòng)設(shè)備建立通信環(huán)境的一種特殊的近距離無(wú)線技術(shù)連接。藍(lán)牙使當(dāng)前的一些便攜移動(dòng)設(shè)備和計(jì)算機(jī)設(shè)備能夠不需要電纜就能連接到互聯(lián)網(wǎng),并且可以無(wú)線接入互聯(lián)網(wǎng)。在生活中也是得到廣泛的應(yīng)用,比如:車(chē)載藍(lán)牙、公共洗衣機(jī)。
- 頻段:2.4—2.485GHz的ISM波段
- 特點(diǎn):(摘選引用自百度百科)
1、藍(lán)牙技術(shù)的適用設(shè)備多,無(wú)需電纜,通過(guò)無(wú)線使電腦和電信連網(wǎng)進(jìn)行通信。
2、藍(lán)牙技術(shù)的工作頻段全球通用,適用于全球范圍內(nèi)用戶(hù)無(wú)界限的使用,解決了蜂窩式移動(dòng)電話(huà)的國(guó)界障礙。
3、藍(lán)牙技術(shù)的安全性和抗干擾能力強(qiáng),由于藍(lán)牙技術(shù)具有跳頻的功能,有效避免了ISM頻帶遇到干擾源。
4、現(xiàn)階段,藍(lán)牙技術(shù)的主要工作范圍在10米左右,經(jīng)過(guò)增加射頻功率后的藍(lán)牙技術(shù)可以在100米的范圍進(jìn)行工作,只有這樣才能保證藍(lán)牙在傳播時(shí)的工作質(zhì)量與效率,提高藍(lán)牙的傳播速度。 - 知識(shí)點(diǎn):
1、Bluetooth
2、廣播 - 難度:初級(jí)
- 效果:
二、操作
????????因?yàn)檫M(jìn)度問(wèn)題,防止勸退初學(xué)者,所以此篇博客只會(huì)描述如何開(kāi)啟藍(lán)牙、打開(kāi)可檢測(cè)設(shè)置和搜索藍(lán)牙,關(guān)于藍(lán)牙連接和藍(lán)牙通信我會(huì)將TCP和UDP數(shù)據(jù)通信放在一起,綜合成一篇進(jìn)階中級(jí)難度的博客。
1、權(quán)限
???????? 需要在 AndroidManifest.xml 中添加以下權(quán)限,防止開(kāi)啟藍(lán)牙失敗,并接收不到提醒。
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
????????主界面.java 權(quán)限二次判斷,在SDK23以上的版本都需要加上這個(gè)權(quán)限判斷,要不然第一次拒絕之后,可能無(wú)法再次彈出提醒,需要用戶(hù)手動(dòng)開(kāi)啟權(quán)限。
private void requestPermission() {
if (Build.VERSION.SDK_INT >= 23 && !isPermissionR){
isPermissionR = true;
ArrayList<String> permissionsList = new ArrayList<>();
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
};
for (String perm : permissions) {
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this,perm)) {
permissionsList.add(perm);
}
}
if (!permissionsList.isEmpty()) {
String[] strings = new String[permissionsList.size()];
ActivityCompat.requestPermissions(MainActivity.this , permissionsList.toArray(strings),0);
}
}
}
2、開(kāi)啟藍(lán)牙
通過(guò)Intent機(jī)制發(fā)送請(qǐng)求,開(kāi)啟藍(lán)牙。
//獲得BluetoothAdapter對(duì)象,啟動(dòng)API
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//判斷本機(jī)是否有藍(lán)牙設(shè)備
if (bluetoothAdapter == null) {
text.setText("本機(jī)無(wú)藍(lán)牙設(shè)備\n");
} else if (!bluetoothAdapter.isEnabled()) {
//若手機(jī)藍(lán)牙未開(kāi)啟,將啟動(dòng)藍(lán)牙設(shè)備
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//發(fā)送請(qǐng)求,開(kāi)啟藍(lán)牙
startActivityForResult(intent , 300);
bluetoothAdapter.cancelDiscovery();
requestPermission();
} else {
Toast.makeText(MainActivity.this , "藍(lán)牙已開(kāi)啟", Toast.LENGTH_SHORT).show();
}
3、可檢測(cè)
只有打開(kāi)可檢測(cè)才能被其他應(yīng)用所檢測(cè)到。
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
showToast("請(qǐng)先開(kāi)啟本機(jī)藍(lán)牙");
return;
}
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
//不可被檢測(cè)性
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//使本機(jī)可在 500秒 內(nèi)可被檢測(cè)到
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
startActivity(intent);
} else {
showToast("本機(jī)已處于被檢測(cè)狀態(tài)!!");
}
4、搜索藍(lán)牙
這里使用Set方法獲取到藍(lán)牙信息。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-486108.html
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
showToast("請(qǐng)先開(kāi)啟本機(jī)藍(lán)牙");
return;
}
foundInfo = "發(fā)現(xiàn)藍(lán)牙設(shè)備:\n"; // 將搜索結(jié)果字符串恢復(fù)成初始值
bluetoothAdapter.startDiscovery();
// 收集藍(lán)牙信息
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0)
{
String pairedInfo = "可配對(duì)的藍(lán)牙設(shè)備:\n";
for(Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext();)
{
BluetoothDevice pairedDevice = (BluetoothDevice)it.next();
//顯示出遠(yuǎn)程藍(lán)牙設(shè)備的名字和物理地址
pairedInfo += pairedDevice.getName()+" "+pairedDevice.getAddress()+"\n";
}
text.setText(pairedInfo);
}
class BluetoothReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//獲得掃描到的遠(yuǎn)程藍(lán)牙設(shè)備
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
foundInfo += device.getName()+" "+device.getAddress()+"\n";
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //搜索結(jié)束
if (foundInfo.equals("發(fā)現(xiàn)藍(lán)牙設(shè)備:\n")) {
Toast.makeText(MainActivity.this , "沒(méi)有搜索到藍(lán)牙設(shè)備" , Toast.LENGTH_SHORT).show();
}
else {
//顯示搜索結(jié)果
text.setText(foundInfo);
text.setMovementMethod(ScrollingMovementMethod.getInstance());
}
}
5、廣播
廣播是藍(lán)牙檢測(cè)中最重要的一環(huán)。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-486108.html
//創(chuàng)建藍(lán)牙廣播信息
bluetoothReceiver = new BluetoothReceiver();
//設(shè)定廣播接收的filter
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//注冊(cè)廣播接收器,當(dāng)設(shè)備被發(fā)現(xiàn)時(shí)調(diào)用函數(shù)
registerReceiver(bluetoothReceiver , filter);
//設(shè)定另一事件廣播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//注冊(cè)廣播接收器
registerReceiver(bluetoothReceiver,filter);
三、附件
1、UI界面設(shè)計(jì)
<?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"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn_kq"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="打開(kāi)藍(lán)牙"
android:background="@drawable/shape"/>
<Button
android:id="@+id/btn_jcx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="啟動(dòng)附近可檢測(cè)"
android:background="@drawable/shape"/>
<Button
android:id="@+id/btn_ss"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="搜索附近可配對(duì)"
android:background="@drawable/shape"/>
<TextView
android:id="@+id/bluetooth_text"
android:layout_width="match_parent"
android:layout_marginTop="40dp"
android:scrollbars="vertical"
android:fadeScrollbars="false"
android:layout_height="wrap_content"/>
</LinearLayout>
2、總代碼
public class MainActivity extends AppCompatActivity {
private Button btnDk,btnKj,btnSs;
private TextView text;
private String foundInfo = null;
//獲得BluetoothAdapter對(duì)象,啟動(dòng)API
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothReceiver bluetoothReceiver;
private boolean isPermissionR = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
text = findViewById(R.id.bluetooth_text);
//開(kāi)啟藍(lán)牙
btnDk = findViewById(R.id.btn_kq);
btnDk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//判斷本機(jī)是否有藍(lán)牙設(shè)備
if (bluetoothAdapter == null) {
text.setText("本機(jī)無(wú)藍(lán)牙設(shè)備\n");
} else if (!bluetoothAdapter.isEnabled()) {
//若手機(jī)藍(lán)牙未開(kāi)啟,將啟動(dòng)藍(lán)牙設(shè)備
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//發(fā)送請(qǐng)求,開(kāi)啟藍(lán)牙
startActivityForResult(intent , 300);
bluetoothAdapter.cancelDiscovery();
requestPermission();
} else {
showToast("藍(lán)牙已開(kāi)啟");
}
}
});
btnKj = findViewById(R.id.btn_jcx);
btnKj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
showToast("請(qǐng)先開(kāi)啟本機(jī)藍(lán)牙");
return;
}
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
//不可被檢測(cè)性
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//使本機(jī)可在 500秒 內(nèi)可被檢測(cè)到
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
startActivity(intent);
} else {
showToast("本機(jī)已處于被檢測(cè)狀態(tài)!!");
}
}
});
btnSs = findViewById(R.id.btn_ss);
btnSs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
showToast("請(qǐng)先開(kāi)啟本機(jī)藍(lán)牙");
return;
}
foundInfo = "發(fā)現(xiàn)藍(lán)牙設(shè)備:\n"; //將搜索結(jié)果字符串恢復(fù)成初始值
bluetoothAdapter.startDiscovery();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0)
{
String pairedInfo = "可配對(duì)的藍(lán)牙設(shè)備:\n";
for(Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext();)
{
BluetoothDevice pairedDevice = (BluetoothDevice)it.next();
//顯示出遠(yuǎn)程藍(lán)牙設(shè)備的名字和物理地址
pairedInfo += pairedDevice.getName()+" "+pairedDevice.getAddress()+"\n";
}
text.setText(pairedInfo);
}
}
});
//創(chuàng)建藍(lán)牙廣播信息
bluetoothReceiver = new BluetoothReceiver();
//設(shè)定廣播接收的filter
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//注冊(cè)廣播接收器,當(dāng)設(shè)備被發(fā)現(xiàn)時(shí)調(diào)用函數(shù)
registerReceiver(bluetoothReceiver , filter);
//設(shè)定另一事件廣播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//注冊(cè)廣播接收器
registerReceiver(bluetoothReceiver,filter);
}
class BluetoothReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//獲得掃描到的遠(yuǎn)程藍(lán)牙設(shè)備
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
foundInfo += device.getName()+" "+device.getAddress()+"\n";
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //搜索結(jié)束
if (foundInfo.equals("發(fā)現(xiàn)藍(lán)牙設(shè)備:\n")) {
Toast.makeText(MainActivity.this , "沒(méi)有搜索到藍(lán)牙設(shè)備" , Toast.LENGTH_SHORT).show();
}
else {
//顯示搜索結(jié)果
text.setText(foundInfo);
text.setMovementMethod(ScrollingMovementMethod.getInstance());
}
}
}
}
public void showToast(String string) {
Toast.makeText(MainActivity.this , string , Toast.LENGTH_SHORT).show();
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= 23 && !isPermissionR){
isPermissionR = true;
ArrayList<String> permissionsList = new ArrayList<>();
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
};
for (String perm : permissions) {
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this,perm)) {
permissionsList.add(perm);
}
}
if (!permissionsList.isEmpty()) {
String[] strings = new String[permissionsList.size()];
ActivityCompat.requestPermissions(MainActivity.this , permissionsList.toArray(strings),0);
}
}
}
}
到了這里,關(guān)于【Android開(kāi)發(fā)基礎(chǔ)】藍(lán)牙信息的獲?。˙luetooth)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!