- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试通过我的应用程序管理多个蓝牙事件,这样用户就不需要离开应用程序并尝试从 Android 设置中搜索/配对蓝牙设备。
我能够枚举以前配对的设备并开始发现,但是我找不到附近的设备。
背景信息:
设备 = 三星盖乐世 S6
操作系统 = Android 6.0.1,内核 3.4.0-750027
蓝牙设备可通过 Android 自己的内置发现发现
这是我的相关代码:
package experiment.xyz.abc;
import android.app.ListActivity;
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.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
*
* This activity is responsible for bluetooth device discovery, pairing, and selection.
* 1) user can search for nearby devices
* 2) pair with device
* 3) unpair a device
* 4) select a bt device( upon successful selection the activity navigates away).
*/
public class BluetDeviceListActivity extends ListActivity
{
public static String BLUETOOTH_DEVICE_ADDRESS= "BLUETOOTH_DEVICE_ADDRESS";
List<BluetoothDevice> bluetList;
BluetoothDeviceListAdapter newBluetoothDeviceListAdapter = null;
private Set<BluetoothDevice> pairedDevices;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluet_list_view);
//instantiate adapter
newBluetoothDeviceListAdapter = new BluetoothDeviceListAdapter(this);
//populate bluet list
populatePairedBluetoothDevices();
//set the ListActivity's adapter with our custom adapter
setListAdapter(newBluetoothDeviceListAdapter);
//on item click get the associated item based index & use Intent to send BluetoothDevice
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice bluetoothDevice= newBluetoothDeviceListAdapter.getListOfBluetoothDevices().get(position);
if (bluetoothDevice!=null) {
Intent returnIntent = new Intent();
returnIntent.putExtra(BLUETOOTH_DEVICE_ADDRESS, bluetoothDevice.getAddress());
setResult(RESULT_OK, returnIntent);
}
finish();
if (mReceiver!=null)
{
try {
unregisterReceiver(mReceiver);
}
catch (IllegalArgumentException exc)
{
exc.printStackTrace();
}
}
}
});
//cancel activity dialog
Button cancelButton = (Button) findViewById(R.id.cancelBluetoothDialogButton);
cancelButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
if (mReceiver!=null)
{
try {
unregisterReceiver(mReceiver);
}
catch (IllegalArgumentException exc)
{
exc.printStackTrace();
}
}
}
});
//search for bluetooth devices
Button searchAndPairButton = (Button) findViewById(R.id.searchPairButton);
searchAndPairButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
//update textview
populateDiscoveredBluetoothDevices();
}
});
//pair or unpair selected device
Button pairOrUnpairButton = (Button) findViewById(R.id.pairUnpairDialogButton);
pairOrUnpairButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO:
}
});
}//end onCreate
//discover nearby devices & add to list
private void populateDiscoveredBluetoothDevices()
{
StreamApiUtility.getBluetoothAdapter();
//is bluet enabled
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
//if already discovering cancel
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
//start a new discovery
mBluetoothAdapter.startDiscovery();
}//end there are paired devices
else
{
Log.i("EEGdataCapture", "No paired devices, select Search & Pair.");
TextView textView =(TextView) findViewById(R.id.textViewBluetoothListInstruction);
textView.setText("No paired devices, select Search & Pair.");
}
}
//query already paired & add to list
private void populatePairedBluetoothDevices()
{
StreamApiUtility.getBluetoothAdapter();
//is bluet enabled
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
//if already discovering cancel
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
//start a new discovery
mBluetoothAdapter.startDiscovery();
//iterate paired/bonded devices and if there are any add them to the custom adapter
pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
BluetoothDevice bluetoothDevice;
Iterator<BluetoothDevice> it = pairedDevices.iterator();
while (it.hasNext()) {
bluetoothDevice = (BluetoothDevice) it.next();
//add to adapter
newBluetoothDeviceListAdapter.addDevice(bluetoothDevice);
newBluetoothDeviceListAdapter.notifyDataSetChanged();
Log.i("EEGdataCapture", "paired device, name: " + bluetoothDevice.getName() + ", address: " + bluetoothDevice.getAddress());
}
}//end there are paired devices
else
{
Log.i("EEGdataCapture", "No paired devices, select Search & Pair.");
TextView textView =(TextView) findViewById(R.id.textViewBluetoothListInstruction);
textView.setText("No paired devices, select Search & Pair.");
}
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device;
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("EEGdataCapture", "BluetoothDevice.ACTION_FOUND");
Log.i("EEGdataCapture", device.getName() + "\n" + device.getAddress());
//update list
newBluetoothDeviceListAdapter.addDevice(device);
newBluetoothDeviceListAdapter.notifyDataSetChanged();
}
else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
Log.i("EEGdataCapture", "BluetoothDevice.ACTION_BOND_STATE_CHANGED");
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast.makeText(MyApp.getAppContext(), "Paired", Toast.LENGTH_SHORT).show();
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED) {
Toast.makeText(MyApp.getAppContext(), "Unpaired", Toast.LENGTH_SHORT).show();
}
}
else if (BluetoothDevice.ACTION_UUID.equals(action)) {
Log.i("EEGdataCapture", "BluetoothDevice.ACTION_UUID");
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.i("EEGdataCapture", "BluetoothAdapter.ACTION_DISCOVERY_STARTED, Discovery Started...");
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.i("EEGdataCapture", "BluetoothAdapter.ACTION_DISCOVERY_FINISHED, Discovery finished.");
}
else
{
Log.i("EEGdataCapture", "BluetoothAdapter, ACTIOM is not supported, action ="+action);
}
}};
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if ( StreamApiUtility.getBluetoothAdapter()!=null) {
StreamApiUtility.getBluetoothAdapter().cancelDiscovery();
}
if (mReceiver!=null)
{
try {
unregisterReceiver(mReceiver);
}
catch (IllegalArgumentException exc)
{
exc.printStackTrace();
}
}
}
@Override
protected void onResume()
{
super.onResume();
//filter to capture bluet events
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//register listener for bluet events before starting discovery again
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReceiver!=null)
{
try {
unregisterReceiver(mReceiver);
}
catch (IllegalArgumentException exc)
{
exc.printStackTrace();
}
}
}
}
更新 list :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
尽管正在调用 ACTION_DISCOVERY_STARTED 或 ACTION_DISCOVERY_FINISHED,但 BroadcastReciever 的 BluetoothDevice.ACTION_FOUND 未被触发/调用。
请帮忙???
谢谢
最佳答案
您的代码似乎没问题。我猜你有 BLUETOOTH
权限(否则你不会收到 ACTION_DISCOVERY_STARTED
)但你是否也有 ACCESS_COARSE_LOCATION
权限?
You need it to receive ACTION_FOUND
:
ACTION_FOUND
Broadcast Action: Remote device discovered.
RequiresBLUETOOTH
andACCESS_COARSE_LOCATION
to receive.
关于Android 的蓝牙 BluetoothDevice.ACTION_FOUND 没有被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39759408/
这个问题在这里已经有了答案: Android 6.0 - Bluetooth - No code exists for Action_Found broadcast intent (1 个回答) 关
我有一个蓝牙设备。 如果: 他们已经配对并连接到设备 它变得不插电 然后它会重新插入 我想自动连接到它。这就是我听 ACTION_FOUND 的原因。 我的代码相当简单。 ACTION_BOND_ST
使用 Log 类跟踪运行时显示 onReceive() 方法没有调用,为什么? 动态注册广播接收器 private void discoverDevices () { Log.e("MOHA
我正在通过实现一项任务来实现蓝牙支持,该任务在后台搜索设备并在搜索完成时提供列表。但是,此列表有时包含 No devices found条目(仅当收到 ACTION_DISCOVERY_FINISHE
我正在尝试计算蓝牙 RSSI 并找到了一些示例,但是 broadcastReceiver 不工作。代码是这样的: private final BroadcastReceiver receiver =
我正在尝试通过我的应用程序管理多个蓝牙事件,这样用户就不需要离开应用程序并尝试从 Android 设置中搜索/配对蓝牙设备。 我能够枚举以前配对的设备并开始发现,但是我找不到附近的设备。 背景信息:
这个简单的广播接收器从不接收任何东西。没有从 BluetoothDevice 发现设备,也没有从 BluetoothAdapter 开始/停止发现。 在代码的前面,我检查蓝牙是否已启用,Bluetoo
更新 我尝试了很多代码,也来自互联网上显示的示例。他们每个人都遵循我的方法。经过几个小时的测试,我得出的结论是在Android 6.0上无法实现未知设备的蓝牙发现,我们只能检索绑定(bind)的设备。
我是一名优秀的程序员,十分优秀!