2014-10-10 36 views
0

所以,我有一個啓動服務的應用程序。此服務開始使用BTAdapter.startDiscovery()掃描藍牙設備。此外,我有一個廣播接收器,它傾聽DISCOVERY_FINISHED動作。如果發生這種情況,我想從我的服務中的onReceive()方法中調用一個方法來重新開始掃描過程。我該怎麼做?如何在廣播接收器中調用服務方法?

這裏我的接收器:

public class PollingReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     ScanBTService sBTs = new ScanBTService(); 
     sBTs.startScan(); 
    } 
} 

和這裏的服務:

public class ScanBTService extends IntentService { 

    private BluetoothAdapter mBTAdapter; 
    private PollingReceiver mPollingReceiver; 

    public ScanBTService() { 
     super("ScanBTService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 
     mBTAdapter = btManager.getAdapter(); 
     mBTAdapter.startDiscovery(); 
    } 

    public void startScan() { 
     try { 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

     mBTAdapter.startDiscovery(); 
    } 
} 

回答

1

在你的onReceive() - 方法,使用下面的兩行重新啓動服務。我沒有測試過,但它應該像那樣工作。

@Override 
public void onReceive(Context context, Intent intent) { 
    //ScanBTService sBTs = new ScanBTService(); 
    //sBTs.startScan(); 
    Intent i = new Intent(getApplicationContext(), ScanBTService.class); 
    startService(i); 
} 

然後,您也可以刪除startScan()方法。

+0

相同bmartins響應。無法解析方法'startService(android.content.Intent)' – alabaster 2014-10-11 13:45:15

0

由於您使用的是IntentService,因此您需要爲啓動的服務創建一個意圖來處理。

這可以通過以下方式實現:

Intent intent = new Intent(context, ScanBTService.class); 
startService(intent); 

如下所述:現在https://developer.android.com/training/run-background-service/send-request.html

,如果你正在尋找有維持藍牙連接的服務,發現設備,發送&接收數據...如果是這樣的話,那麼根據我的經驗,我會爭論以下幾點:

希望它可以幫助 乾杯

+0

不幸的是,它不工作。我得到的錯誤:無法解析方法'startService(android.content.Intent)' – alabaster 2014-10-11 12:14:43

+0

@alabaster,你可能會在這裏被問到的東西以外的其他東西丟失。你需要一個上下文來進行這個調用。也許context.startService(intent)?,或者你聲明你的服務在清單中? – bmartins 2014-10-15 13:08:46

1

試試這個解決方法:

context.startService(new Intent(context, ScanBTService.class);

+2

雖然這個回覆可能會或可能不會提供有效的提示,但它不是一個答案。請考慮閱讀[回答](http://stackoverflow.com/help/how-to-answer)上的幫助文件。 – user3078414 2016-07-15 17:34:54