前言
Hello,現(xiàn)在的工作苫拍,必須要學(xué)習(xí)Bluetooth的一些使用,在這里記錄一下
一.藍牙權(quán)限
不管如何,開發(fā)藍牙,首先加上權(quán)限再說
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
二.藍牙API
1.BluetoothAdapter
本地藍牙適配器(如:自己的手機)
2.BlueDevice
遠程藍牙(如:一個藍牙音箱)
3.BluetoothSocket
藍牙socket的接口
4.BluetoothServerSocket
開放的服務(wù)器socket睦袖,它監(jiān)聽接受的請求(與TCP ServerSocket類似)
三.使用
1.BluetoothAdapter下的方法
//開始搜索
startDiscovery()
//取消搜索
cancelDiscovery()
//直接打開藍牙
enable()
//直接關(guān)閉藍牙
disable()
//彈窗申請權(quán)限打開藍牙
Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler,reCode);
//獲得本地藍牙名字
getName()
//本地藍牙地址
getAddress()
//獲取本地藍牙適配器
getDefaultAdapter()
//根據(jù)藍牙地址獲取遠程藍牙設(shè)備
getRemoteDevice(String address)
//獲取本地藍牙適配器當(dāng)前狀態(tài)
getState()
//判斷當(dāng)前是否正在查找設(shè)備
isDiscovering()
//判斷藍牙是否打開
isEnabled()
//根據(jù)名稱珊肃,UUID創(chuàng)建并返回BluetoothServerSocket
listenUsingRfcommWithServiceRecord(String name,UUID uuid)
2.實際使用
// 獲取本地藍牙適配器
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//獲得本地藍牙name和mac地址
mBluetoothAdapter.getName();
mBluetoothAdapter.getAddress();
// 判斷有沒有藍牙硬件支持
if (mBluetoothAdapter == null) {
Toast.makeText(this, "設(shè)備不支持藍牙", Toast.LENGTH_SHORT).show(); finish();
}
// 判斷是否打開了藍牙
if (!mBluetoothAdapter.isEnabled()) {
// 我們通過startActivityForResult()方法發(fā)起的Intent將會在onActivityResult()回調(diào)方法中獲取用戶的選擇,比如用戶單擊了Yes開啟,
// 那么將會收到RESULT_OK的結(jié)果伦乔,
// 如果RESULT_CANCELED則代表用戶不愿意開啟藍牙
// 彈出對話框提示用戶是否打開
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
// 沒有提示強制打開藍牙(用enable()方法來開啟厉亏,無需詢問用戶(實惠無聲息的開啟藍牙設(shè)備),這時就需要用到android.permission.BLUETOOTH_ADMIN權(quán)限)
// mBluetoothAdapter.enable();
// 獲取已經(jīng)配對的設(shè)備
Set<BluetoothDevice> myDevices = mBluetoothAdapter.getBondedDevices();
// 判斷是否有配對過的設(shè)備
if (myDevices.size() > 0) {
for (BluetoothDevice device : myDevices ) {
// 遍歷到列表中
tv_devices.append(device.getName() + ":" + device.getAddress());
Log.i("已配對設(shè)備", tvDevices.getText().toString());
}
}
// 獲得連接中藍牙的name和mac地址
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String bltname= device.getName().toString();
String bltmac= device.getAddress().toString();
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"
tools:context="com.example.zxnet.mybluetoothdome.MainActivity">
<Button
android:id="@+id/btn_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="搜索藍牙設(shè)備"
android:background="#54FF9F"
/>
<ListView
android:id="@+id/mylistview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_search"
android:textSize="18sp"
/>
</RelativeLayout>
MainActivity.class類
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "MainActivity";
// 本地藍牙適配器
private BluetoothAdapter mBluetoothAdapter;
// 搜索按鈕
private Button btn_search;
//搜索到藍牙顯示列表
private ListView mylistview;
// listview的adapter
private ArrayAdapter<String> mylistAdapter;
// 存儲搜索到的藍牙
private List<String> bluetoothdeviceslist = new ArrayList<String>();
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBluetoothPermission();
initview();
SearchBluetoot();
}
private void initview() {
mylistview = (ListView) findViewById(R.id.mylistview);
btn_search = (Button) findViewById(R.id.btn_search);
// 獲取本地藍牙適配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btn_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setTitle("正在搜索...");
// 判斷是否在搜索,如果在搜索,就取消搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 開始搜索
mBluetoothAdapter.startDiscovery();
}
});
}
public void SearchBluetoot() {
// 判斷有沒有藍牙硬件支持
if (mBluetoothAdapter == null) {
Toast.makeText(this, "設(shè)備不支持藍牙", Toast.LENGTH_SHORT).show();
finish();
}
// 判斷是否打開了藍牙
if (!mBluetoothAdapter.isEnabled()) {
// 我們通過startActivityForResult()方法發(fā)起的Intent將會在onActivityResult()回調(diào)方法中獲取用戶的選擇烈和,比如用戶單擊了Yes開啟爱只,
// 那么將會收到RESULT_OK的結(jié)果,
// 如果RESULT_CANCELED則代表用戶不愿意開啟藍牙
// 彈出對話框提示用戶是否打開
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
// 沒有提示強制打開藍牙(用enable()方法來開啟招刹,無需詢問用戶(實惠無聲息的開啟藍牙設(shè)備),這時就需要用到android.permission.BLUETOOTH_ADMIN權(quán)限)
// mBluetoothAdapter.enable();
// 獲的已經(jīng)配對的設(shè)備
Set<BluetoothDevice> myDevices = mBluetoothAdapter.getBondedDevices();
/// 判斷是否有配對過的設(shè)備
if (myDevices.size() > 0) {
for (BluetoothDevice device : myDevices) {
// 遍歷到列表中
bluetoothdeviceslist.add(device.getName() + ":" + device.getAddress() + "\n");
}
}
// adapter
mylistAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, bluetoothdeviceslist);
mylistview.setAdapter(mylistAdapter);
// 找到設(shè)備的廣播
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// 注冊廣播
registerReceiver(myreceiver, filter);
// 搜索完成的廣播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
// 注冊廣播
registerReceiver(myreceiver, filter);
}
}
// 廣播接收器
private final BroadcastReceiver myreceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 收到的廣播類型
String action = intent.getAction();
// 發(fā)現(xiàn)設(shè)備的廣播
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 從intent中獲取設(shè)備
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 判斷是否配對過
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
// 添加到列表
bluetoothdeviceslist.add(device.getName() + ":"+ device.getAddress() + "\n");
mylistAdapter.notifyDataSetChanged();
}
// 搜索完成
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setTitle("搜索完成恬试!");
}
}
};
/*
校驗藍牙權(quán)限
*/
private void checkBluetoothPermission() {
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M) {
// Android M Permission check
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_COARSE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
}
break;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
以上就是藍牙基礎(chǔ)的使用,也比較簡單,要開發(fā)藍牙,這些是必須了解的,要想了解更多,請仔細看官方的api開發(fā)文檔,如果對你有幫助,請點個贊吧!!
EDN