我试图使用蓝牙找到附近的设备,该代码适用于Android版本4和5.0.2,但是当在三星galaxy s7和s8(都是版本7)上尝试相同的代码时,我可以看到广播接收器的信息“ ACTION_DISCOVERY_STARTED“和”ACTION_DISCOVERY_FINISHED“,但他们无法找到任何设备。
代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
}
adapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts
showToast("BroadcastReceiver" + " ACTION_DISCOVERY_STARTED");
Log.v("BroadcastReceiver", "ACTION_DISCOVERY_STARTED");
} else if
(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes
Log.v("BroadcastReceiver", "ACTION_DISCOVERY_FINISHED");
showToast("BroadcastReceiver" + "ACTION_DISCOVERY_FINISHED");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice)
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.v("Found device ", "Found device " + device.getName());
showToast("Found device " + device.getName());
}
}
};
menifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ramile.myapplication">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>