无法从服务运行蓝牙发现
问题描述:
我无法从服务运行startDiscovery(对于蓝牙)。 服务从睡眠运行WakefulBroadcastReceiver(由计时器)。服务 的源代码:无法从服务运行蓝牙发现
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "LocationService";
private BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service onCreate");
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBTReceiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service onStartCommand");
BTscanner();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(mBTReceiver);
}
private void BTscanner() {
Log.e(TAG, "==BT: Run BTscanner");
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
Log.e(TAG, "==BT: End BTscanner");
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e(TAG, "==BT: Started");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e(TAG, "==BT: Finished");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "==BT: " + device.getAddress());
}
}
};
}
在日志中,我看到:
Service onStartCommand
==BT: Run BTscanner
==BT: End BTscanner
但不`吨看到:已发现的设备
==BT: Started
==BT: Finished
和列表。
在清单所有权限安装:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
和服务清单的应用领域启用:
<service
android:name=".LocationService"
android:enabled="true"
android:exported="true" />
我做了什么错? Tnx。
答
我想,我找到了一个解决方案。
我在智能手机上安装并运行带有活动蓝牙的应用程序时出现问题。
安装应用程序和手动停用/激活蓝牙设备后,所有工作正常。
也许这是某种硬件故障。
然后重新安装两次应用程序,并且不会重复该问题。
答
您是否确定您的接收器尚未在onDestroy方法中取消注册,然后才有时间处理任何操作?我会在其中设置一个断点来看看那里发生了什么?
我给所有的方法都设置了一个断点。一切正常。 – user2956492