本文介绍了绑定到一个服务的多个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务组件(我所有应用程序的通用任务),它可以被任何应用程序调用.我试图从所有活动中访问服务对象,我注意到创建服务的人 [startService(intent)] 具有正确的信息.但是休息并没有得到所需的信息.我的代码如下:

I have a service component (common task for all my apps), which can be invoked by any of the apps. I am trying to access the service object from the all activities, I noticed that the one which created the service [startService(intent)] has the right informaion. But rest does not get the informaion needed. My Code is as below:

// 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).它会创建一个新服务并与其他服务并行运行.

If I invoke startService(intent). it creates a new service and runs in parallel to the other service.

如果我不调用 startService(intent),serviceObj.getData() 返回空值.

If I don't invoke startService(intent), serviceObj.getData() retuns null value.

谁能告诉我我哪里出错了.

Can any one enlighten me where have I gone wrong.

任何类型的指针都会非常有用..

Any kind of pointer will be very useful..

谢谢和问候,维奈

推荐答案

不,它没有.您的服务最多只有一个实例在运行.

No, it does not. There will be at most one instance of your service running.

如果我不调用 startService(intent),serviceObj.getData() 返回空值.

startService() 与它无关,从我阅读你的代码来看.您正试图在 onCreate() 中使用 serviceObj.那永远行不通.bindService() 是一个异步调用.在调用 onServiceConnected() 之前,您不能使用 serviveObj.onServiceConnected() 直到 onCreate() 返回后的某个时间才会被调用.

startService() has nothing to do with it, from my reading of your code. You are attempting to use serviceObj in onCreate(). That will never work. bindService() is an asynchronous call. You cannot use serviveObj until onServiceConnected() is called. onServiceConnected() will not be called until sometime after onCreate() returns.

还有:

  • 虽然在某些情况下您可能同时需要 startService()bindService(),但在正常情况下它们并不都需要.
  • 不要使用getApplicationContext().
  • While there are cases when you might need both startService() and bindService(), they are not both needed in the normal case.
  • Do not use getApplicationContext().

这篇关于绑定到一个服务的多个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-16 19:28