简体   繁体   English

需要有关活动和服务行为的建议

[英]Need advices for Activity and Service behavior

My question is rather theoric, in fact I already saw examples on how to bind or how to start an Activity with a service but I still don't get one thing: I wrote a Service that is bounded to an activity and I'm wondering how to get the activity that called the bindService() method from this service. 我的问题是理论上的,实际上我已经看过有关如何绑定或如何使用服务启动活动的示例,但我仍然一无所获:我写了一个与活动绑定的服务,我想知道如何从此服务获取调用bindService()方法的活动。

My purpose is to get an object that will be necessary to the service because I want it to listen for networks messages in background, as this object is quite complicated to parcel I'd rather get the activity that contains it. 我的目的是要获得服务所必需的对象,因为我希望它在后台侦听网络消息,因为该对象的包裹非常复杂,所以我宁愿获得包含它的活动。
Is there any call possible to the current context? 当前上下文是否可以调用?

Thanks for your answers. 感谢您的回答。

If your service is only used within your application and by only one process at a time, you can try to use a bound service. 如果您的服务仅在应用程序中使用,并且一次仅由一个进程使用,则可以尝试使用绑定的服务。 in the IBinder interface used to communicate between the activity and the service implements a public method that returns the local service. 用于在活动和服务之间进行通信的IBinder接口中的IBinder实现了返回本地服务的公共方法。 This IBinder will be given to the activity through the onServiceConnected() callback. IBinder将通过onServiceConnected()回调提供给活动。 At this point the activity can get the Service object and call on it a public method to pass the object that you want. 此时,活动可以获取Service对象,并在其上调用一个公共方法以传递所需的对象。

public class MyService extends Service {

    private final IBinder mBinder = new MyBinder(); //singleton

    private MyObject mObject;

    public class MyBinder extends Binder {
        MyService getService() {
            return this;
        }
    }

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

    public void setMyObject(MyObject mObject) {
      this.mObject = mObject;
    }
}

Hope this works for you. 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM