我有一個服務組件(適用於我所有應用程序的常見任務),它可以由任何應用程序調用。我試圖從所有活動中訪問服務對象,我注意到創建服務[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()會返回空值。
任何人都可以啓發我在哪裏出錯了。
任何類型的指針將是非常有用的..
感謝和問候, 維奈
感謝您的回覆。它幫助了我。 關於與其他服務並行運行的服務,我發現這是由於「新的Intent(this.context,Service.class)」。 我用「new Intent(」com.package「,」com.package.service「)替換了這個;」 感謝您的指點.. – Vinay 2010-08-06 06:48:28
您的意思是「不要使用getApplicationContext」。那麼,這是否適用於http://stackoverflow.com/questions/3141632/android-service-interacting-with-multiple-activities的接受答案呢?我的答案是「錯誤」/違反規則嗎? – OneWorld 2013-07-04 14:26:58
@OneWorld:我絕對不是「應用程序」中的「活動」來追蹤「當前」活動「模式的粉絲。如果沒有其他的話,一個靜態數據成員的工作就會更好,並且具有更大的靈活性除此之外,防止「活動」被垃圾收集是麻煩的處方。 – CommonsWare 2013-07-04 15:00:04