2017-08-21 88 views
0

我有一個Service可以掃描BLE設備。 Activity應顯示Service收集的一些數據。服務開始時會收到通知

A Receiver已執行,待啓用Bluetooth時予以通知,以便我們知道何時啓動Service

如果Service正在運行,並且打開了Activity,則它只執行bindService()。但是,如果Service未運行(因爲Bluetooth已禁用),應用程序將被打開並啓用Bluetooth,因爲綁定進程已被跳過,所以它不會爲bind

如何在啓動時通知Service啓動或自動綁定?

謝謝。

回答

1

您可以使用LocalBroadCastManager將broadcast從您的服務發送到您的活動。

助手註冊併發送Intents廣播到您的過程中的本地對象。與使用sendBroadcast(意圖)發送全球廣播相比,這具有許多優點:

0

您可以使用本地廣播接收器從您的服務。

0

在服務中使用這些代碼

intent = new Intent("my-integer"); 
    intent.putExtra("message",""+a); 
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 

在你的活動中使用此代碼

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Extract data included in the Intent 
     String data = intent.getStringExtra("message"); 
      if (!data.equals("0")) { 
      //Do something 
      } else { 
      //Do something else 
      } 
     } 

    } 
}; 
相關問題