在Android中,如何从Service传递自定义对象到Activity?

6
我正在使用asmack为安卓开发即时通讯应用。我已经启动了一个聊天服务,该服务连接到了xmpp服务器,并能够获取好友列表和在线状态。但现在我需要更新UI并将帐户对象列表从服务传递到活动中。我找到了Parcelable和Serializable两种方法,但无法确定哪种是正确的选择。是否有人可以提供一些代码示例,以便我可以完成这个任务呢?
谢谢!

1
https://dev59.com/42865IYBdhLWcg3wkfcWorhttp://stackoverflow.com/questions/9239240/passing-object-through-intent-from-background-service-to-an-activity - owen gerig
1个回答

1

你正在开发一个不错的应用。我对Smack不是很了解,但我知道如何从服务传递对象到Activity。你可以为你的服务创建AIDL文件。AIDL将把你的服务对象传递给Activity。然后你就可以更新你的Activity界面。这个链接可能对你有帮助!

首先,你需要使用编辑器创建.aidl文件,并将此文件保存在桌面上。AIDL就像一个接口一样,没有别的东西。比如,ObjectFromService2Activity.aidl

package com.yourproject.something

// Declare the interface.
interface ObjectFromService2Activity {
    // specify your methods 
    // which return type is object [whatever you want JSONObject]
    JSONObject getObjectFromService();

}

现在将此文件复制并粘贴到您的项目文件夹中,ADT插件将自动生成ObjectFromService2Activity接口和存根在gen/文件夹中。

Android SDK还包括一个(命令行)编译器aidl(在tools/目录中),如果您不使用Eclipse,则可以使用它来生成java代码。

覆盖您的服务中的obBind()方法。例如,Service1.java

public class Service1 extends Service {
private JSONObject jsonObject;

@Override
public void onCreate() {
  super.onCreate();
  Log.d(TAG, "onCreate()");
  jsonObject = new JSONObject();
}

@Override
public IBinder onBind(Intent intent) {

return new ObjectFromService2Activity.Stub() {
  /**
   * Implementation of the getObjectFromService() method
   */
  public JSONObject getObjectFromService(){
    //return your_object;
    return jsonObject;
  }
 };
}
@Override
public void onDestroy() {
   super.onDestroy();
   Log.d(TAG, "onDestroy()");
 }
}

使用您的活动或想要启动此服务的位置启动您的服务,并创建ServiceConnection。例如,

Service1 s1;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Following the example above for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service
        s1 = ObjectFromService2Activity.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        s1 = null;
    }
};

使用ObjectFromService2Activity对象,您可以访问方法s1.getObjectFromService(),该方法将返回JSONObject。更多帮助 有趣!


我也研究了BroadcastReceiver,因为它可以通过可序列化的extra在Intent中传递对象。我能否使用此方法将对象传递给Activity?另外,您有一些关于AIDL的好例子吗? - navraj
当您需要执行IPC时,使用Messenger作为接口比使用AIDL实现更简单,因为Messenger将所有调用排队到服务中,而纯AIDL接口会向服务发送同时请求,然后必须处理多线程。对于大多数应用程序,服务不需要执行多线程,因此使用Messenger允许服务一次处理一个调用。如果您的服务需要多线程,则应使用AIDL定义您的接口。 - Mahesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接