概述
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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.hanqi.bluetooth.MainActivity" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="搜索蓝牙设备" android:onClick="bt_OnClick"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvDevices" /> </LinearLayout>
package com.hanqi.bluetooth; 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.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.Set; public class MainActivity extends AppCompatActivity { TextView tvDevices; BluetoothAdapter mBluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvDevices=(TextView)findViewById(R.id.tvDevices); //获取本地蓝牙适配器 mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> paireDevices=mBluetoothAdapter.getBondedDevices(); if (paireDevices.size()>0) { for (BluetoothDevice device:paireDevices) { tvDevices.append(device.getName()+":"+device.getAddress()); } } IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(receiver,filter); filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(receiver,filter); } public void bt_OnClick(View v) { setProgressBarIndeterminateVisibility(true); setTitle("正在扫描..."); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } mBluetoothAdapter.startDiscovery(); } private final BroadcastReceiver receiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action=intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState()!=BluetoothDevice.BOND_BONDED) { tvDevices.append(device.getName()+":"+device.getAddress()); } }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarVisibility(false); setTitle("已搜索完成"); } } }; }
转载于:https://www.cnblogs.com/jiang2538406936/p/5678081.html
最后
以上就是笨笨大碗为你收集整理的旺仔:Android的蓝牙技术(一)(Genymotion模拟器测试没有实现)的全部内容,希望文章能够帮你解决旺仔:Android的蓝牙技术(一)(Genymotion模拟器测试没有实现)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复