简体   繁体   English

如何在多个活动中使用服务?

[英]how to use a service in multiple activities?

I'm having a problem writing a service, that should work with multiple activities.我在编写服务时遇到问题,该服务应该适用于多种活动。 I wrote a simple service and a mediator class the makes the bind and can return a service object.我写了一个简单的服务和一个中介 class 进行绑定并可以返回一个服务 object。 this is the simple service class:这是简单的服务 class:

public class ServerConnectionService extends Service{

private static final String TAG = "ServerConnectionService";
private final Binder binder=new LocalBinder();

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onDestroy(){
    super.onDestroy();
}

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

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

this is the mediator class:这是中介 class:

public class ServiceConnectionBinder{

private ServerConnectionService m_SrvConnection=null;
private ServiceConnection m_OnService;
private boolean m_IsBound;
private Activity m_Client;

public ServiceConnectionBinder(Activity  i_Activity)
{
    m_IsBound = false;
    this.m_Client = i_Activity;
    this.m_OnService=new ServiceConnection() {
        public void onServiceConnected(ComponentName className,IBinder rawBinder) {
                m_SrvConnection=((ServerConnectionService.LocalBinder)rawBinder).getService();
            }

            public void onServiceDisconnected(ComponentName className) {
                m_SrvConnection=null;
            }
        };

    doBindService();
    Log.d("ServiceConnectionBinder", "finished Ctor");
}

private void doBindService() {
    if(!m_IsBound)
    {
        m_Client.bindService(new Intent(m_Client, ServerConnectionService.class), m_OnService, Context.BIND_AUTO_CREATE);
        m_IsBound = true;
    }

    if(m_SrvConnection == null)
    {
        Log.d("ServiceConnectionBinder",".doBindService cannot bind " + ServerConnectionService.class.toString() + " to " + this.toString());
    }
}

public void doUnbindService() {
    if (m_IsBound) {
        // Detach our existing connection.
        m_Client.unbindService(m_OnService);
        m_IsBound = false;
    }
}

public ServerConnectionService getServerConnectionService()
{
    if(m_IsBound)
    {
        Log.d("ServiceConnectionBinder", "getServerConnectionService m_IsBound = " + m_IsBound); 
    }
    return m_SrvConnection;
}
}

The client Activity has the following data members:客户端 Activity 具有以下数据成员:

private ServiceConnectionBinder m_SrvcConnectionBinder=null;
private ServerConnectionService m_SrvConnection=null;

And in onCreate() the following code:在 onCreate() 中,代码如下:

m_SrvcConnectionBinder = new ServiceConnectionBinder(this);
m_SrvConnection = m_SrvcConnectionBinder.getServerConnectionService();

problem is that after the onCreate(), the m_SrvConnection is always null .问题是在 onCreate() 之后, m_SrvConnection 总是 null

If you have any other ways to implement this you are more than welcome to share..如果您有任何其他方法来实现这一点,非常欢迎您分享..

Resurrecting the old post as I had the similar question, but there is no clear answer here.复活旧帖子,因为我有类似的问题,但这里没有明确的答案。 One of the ways to address this is like this:解决这个问题的方法之一是这样的:

protected void onCreate(Bundle savedInstanceState){
    //... some stuff #1...

    new AsyncTask<Void, Void, Integer>(){
        protected void onPreExecute() { }
        protected Integer doInBackground(Void... params) {
            while(m_SrvConnection==null);
            return new Integer(1);
        }
        protected void onPostExecute(Integer result) {
             // service is up, m_SrvConnection is set
             // what you wanted to do with the service in onCreate() goes here
        }
     }.execute();

    //...some stuff #2...
}

Note that "some stuff #1" will run right when onCreate() is called, "some stuff #2" will be executed almost right after that, but what you put in onPostExecute() will be run much later.请注意,当 onCreate() 被调用时,“some stuff #1”将正确运行,“some stuff #2”将在之后几乎立即执行,但您放入 onPostExecute() 的内容将在更晚的时候运行。

The reason for doing it this way and not just putting the code into onServiceConnected() is that the ServiceConnectionBinder can now be put outside of the Activity (in some singleton, or Application for example) and be used by multiple activities without the need for each of them to bind to the service.这样做而不只是将代码放入 onServiceConnected() 的原因是,ServiceConnectionBinder 现在可以放在 Activity 之外(例如在某些 singleton 或应用程序中),并且可以由多个活动使用,而无需每个活动其中绑定到服务。

Note, it may not be obvious, but things in onPostExecute() may (will) actually be run after all other standard callbacks (like onResume() etc.).请注意,这可能并不明显,但 onPostExecute() 中的内容实际上可能(将)在所有其他标准回调(如 onResume() 等)之后运行。

problem is that after the onCreate(), the m_SrvConnection is always null.问题是在 onCreate() 之后,m_SrvConnection 总是 null。

Of course.当然。 The binding request will not even begin until the main application thread gets control again (ie, you return control to the OS).绑定请求甚至不会开始,直到主应用程序线程再次获得控制权(即,您将控制权返回给操作系统)。

You cannot use m_SrvConnection until onServiceConnected() is called.在调用onServiceConnected()之前,您不能使用m_SrvConnection

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

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