2016-01-28 64 views
0

我無法從服務運行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。

回答

0

我想,我找到了一個解決方案。

我在智能手機上安裝並運行帶有活動藍牙的應用程序時出現問題。

安裝應用程序和手動停用/激活藍牙設備後,所有工作正常。

也許這是某種硬件故障。

然後重新安裝兩次應用程序,並且不會重複該問題。

0

您是否確定您的接收器尚未在onDestroy方法中取消註冊,然後纔有時間處理任何操作?我會在其中設置一個斷點來看看那裏發生了什麼?

+0

我給所有的方法都設置了一個斷點。一切正常。 – user2956492