【问题标题】:Multiple activities binding to a service绑定到服务的多个活动
【发布时间】:2010-08-03 12:06:41
【问题描述】:

我有一个服务组件(我的所有应用程序的共同任务),它可以被任何应用程序调用。我正在尝试从所有活动中访问服务对象,我注意到创建服务 [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 值。

谁能告诉我哪里出错了。

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

感谢和问候, 维奈

【问题讨论】:

    标签: android binding service android-activity


    【解决方案1】:

    如果我调用 startService(intent)。它会创建一个新服务并与其他服务并行运行。

    不,它没有。您的服务最多会运行一个实例。

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

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

    还有:

    • 虽然在某些情况下您可能同时需要 startService()bindService(),但在正常情况下并不都需要它们。
    • 请勿使用getApplicationContext()

    【讨论】:

    • 感谢您的回复。它帮助了我。关于与另一个并行运行的服务,我发现这是由于“new Intent(this.context,Service.class)”造成的。我将其替换为“新意图(“com.package”,“com.package.service”);”谢谢指点。。
    • 您在说“不要使用 getApplicationContext”。那么,这也适用于stackoverflow.com/questions/3141632/… 的公认答案吗?我的答案“错误”/违反了那里的规则?
    • @OneWorld:我绝对不喜欢“在Application 中粘贴Activity 以跟踪“当前”活动”模式。如果不出意外,静态数据成员也可以工作,并且具有更大的灵活性。除此之外,防止Activity 被垃圾收集是解决问题的良方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多