Android开发之蓝牙--扫描已经配对的蓝牙设备
一.?什么是藍牙(Bluetooth)?
?
1.1??BuleTooth是目前使用最廣泛的無線通信協議
?
1.2??主要針對短距離設備通訊(10m)
?
1.3??常用于連接耳機,鼠標和移動通訊設備等.
?
二.?與藍牙相關的API
?
2.1?BluetoothAdapter:
代表了本地的藍牙適配器
?
2.2?BluetoothDevice
代表了一個遠程的Bluetooth設備
?
三.?掃描已經配對的藍牙設備(1)
?
注:必須部署在真實手機上,模擬器無法實現
?
首先需要在AndroidManifest.xml?聲明藍牙權限
?
<user-permission?android:name="android.permission.BLUETOOTH"?/>
?
配對藍牙需要手動操作:
?
1.?打開設置-->?無線網絡?-->?藍牙?勾選開啟
?
2.?打開藍牙設置??掃描周圍已經開啟的藍牙設備(可以與自己的筆記本電腦進行配對),點擊進行配對
?
?
?電腦上會彈出提示窗口:?添加設備
?
?顯示計算與設備之間的配對碼,要求確認是否配對
?
?手機上也會顯示類似的提示.?
?
四.?掃描已經配對的藍牙設備(2)
?
4.1?獲得BluetoothAdapter對象
4.2?判斷當前移動設備中是否擁有藍牙
4.3?判斷當前移動設備中藍牙是否已經打開
4.4?得到所有已經配對的藍牙設備對象
?
import java.util.Iterator; import java.util.Set;import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;public class MainActivity extends Activity {private Button button = null;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);button = (Button)findViewById(R.id.buttonId);button.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {//獲得BluetoothAdapter對象,該API是android 2.0開始支持的BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();//adapter不等于null,說明本機有藍牙設備if(adapter != null){System.out.println("本機有藍牙設備!");//如果藍牙設備未開啟if(!adapter.isEnabled()){Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//請求開啟藍牙設備startActivity(intent);}//獲得已配對的遠程藍牙設備的集合Set<BluetoothDevice> devices = adapter.getBondedDevices();if(devices.size()>0){for(Iterator<BluetoothDevice> it = devices.iterator();it.hasNext();){BluetoothDevice device = (BluetoothDevice)it.next();//打印出遠程藍牙設備的物理地址System.out.println(device.getAddress());}}else{System.out.println("還沒有已配對的遠程藍牙設備!");}}else{System.out.println("本機沒有藍牙設備!");}}});} }
轉載于:https://www.cnblogs.com/lhj588/p/3610445.html
總結
以上是生活随笔為你收集整理的Android开发之蓝牙--扫描已经配对的蓝牙设备的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Screen会话命令 Linux
- 下一篇: 股票死亡谷是什么意思