无法从Service运行BlueTooth发现

时间:2016-01-28 10:01:32

标签: android service bluetooth broadcastreceiver

我无法从Service运行startDiscovery(对于BlueTooth)。 服务通过 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

以及已发现设备的列表。

Manifest 中安装了所有权限:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

并在Manifest的应用程序字段中启用了服务:

<service
            android:name=".LocationService"
            android:enabled="true"
            android:exported="true" />

我做错了什么? TNX。

2 个答案:

答案 0 :(得分:0)

在有时间处理任何操作之前,您确定您的接收器尚未在onDestroy方法中取消注册吗?我会在其中加上一个突破点,看看那里发生了什么?

答案 1 :(得分:0)

我想,我找到了解决方案。

在智能手机上使用有源蓝牙安装和运行应用程序时出现问题。

安装应用程序并手动停用/激活蓝牙设备后,一切正常。

可能是某种硬件故障。

然后重新安装应用程序两次,问题不再重复。