Fra*_*zzi 6 android bluetooth discovery
UPDATE
我尝试了许多代码,也是从互联网上显示的例子.他们每个都遵循我的方法.经过几个小时的测试,我得出结论,在Android 6.0上没有机会实现未知设备的蓝牙发现,我们只能检索绑定的设备.我很确定这个Android版本有什么东西.
如果有人知道如何解决这个问题,我真的很感激任何帮助.
原帖
我的代码工作正常,但没有找到设备.我只收到DISCOVERY_STARTED和DISCOVERY_FINISHED,因此找不到任何设备,但使用系统应用程序可以找到这些设备.
这是我的应用程序的代码,希望它可以提供帮助.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
//other stuff...
IntentFilter filter=new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(myreceiver,filter);
}
final BroadcastReceiver myreceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("test","RECEIVED: "+ action);
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
}
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("test", device.getName() + "\n" + device.getAddress());
}
}};
public void scanDevices(View v){
if (bluetoothAdapter.isEnabled()){
bluetoothAdapter.startDiscovery();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经设置了权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)
Fra*_*zzi 11
很简单的解决方案
1.为清单添加FINE_LOCATION权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)
2.在运行时请求FINE_LOCATION权限:
//since i was working with appcompat, i used ActivityCompat method, but this method can be called easily from Activity subclassess.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSION_REQUEST_CONSTANT);
Run Code Online (Sandbox Code Playgroud)
3.实现onRequestPermissionsResult方法:
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CONSTANT: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted!
}
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都是因为棉花糖需要此权限才能使用蓝牙进行发现.
由于此权限属于Dangerous权限组,因此只需在清单中声明它不起作用,我们需要用户明确同意使用该位置(即使我们实际上不需要该位置).
| 归档时间: |
|
| 查看次数: |
1920 次 |
| 最近记录: |