簡體   English   中英

綁定到服務的多個活動

[英]Multiple activities binding to a service

我有一個服務組件(我所有應用程序的共同任務),可以由任何應用程序調用。 我正在嘗試從所有活動訪問服務對象,我注意到創建服務[startService(intent)]的對象具有正確的信息。 但是休息並不能獲得所需的信息。 我的代碼如下:

// Activity.java
public void onCreate(Bundle savedInstanceState) {
    ...

    Intent intent = new Intent (this.context, Service.class) ;
    this.context.startService(intent) ;
    this.context.bindService(intent, this, Context.BIND_AUTO_CREATE) ;
    ...
    String result = serviceObj.getData() ;
}

public void onServiceConnected(ComponentName name, IBinder service) {
    serviceObj = ((Service.LocalBinder)service).getService();
    timer.scheduleAtFixedRate(task, 5000, 60000 ) ;
}



// Service.java

private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
    Service getService() {
        return Service.this;
    }
}

public void onCreate() {
    super.onCreate();
    context = getApplicationContext() ;
}

public void onStart( Intent intent, int startId ) {

... some processing is done here...

}

public IBinder onBind(Intent intent) {
    return mBinder;
}

如果我調用startService(intent)。 它創建一個新服務並與其他服務並行運行。

如果我不調用startService(intent),則serviceObj.getData()重新調整null值。

任何人都可以啟發我哪里做錯了。

任何一種指針都將非常有用。

感謝和問候,Vinay

如果我調用startService(intent)。 它創建一個新服務並與其他服務並行運行。

不,不是的。 您的服務最多將運行一個實例。

如果我不調用startService(intent),則serviceObj.getData()重新調整null值。

根據我對代碼的閱讀, startService()與它無關。 您正在嘗試在onCreate()使用serviceObj 那永遠都行不通。 bindService()是一個異步調用。 在調用onServiceConnected()之前,不能使用serviveObj 直到onCreate()返回后的某個時間才會調用onServiceConnected()

也:

  • 在某些情況下,您可能同時需要startService()bindService() ,但在通常情況下並不需要。
  • 不要使用getApplicationContext()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM