Android将自定义对象从服务传递给活动

Posted

技术标签:

【中文标题】Android将自定义对象从服务传递给活动【英文标题】:Android Pass Custom Object from Service to activity 【发布时间】:2012-05-23 13:57:25 【问题描述】:

我正在使用 asmack 创建一个适用于 android 的 Instant Messenger。 我已经启动了一个连接到 xmpp 服务器的聊天服务。 该服务连接到 xmpp 服务器,我正在获取名册和存在。 但现在我必须更新 UI 并将帐户对象列表从服务传递到活动。我遇到了 Parcelable 和可序列化的。 我无法弄清楚这项服务的正确方法是什么。 有人可以提供一些我可以做的代码示例吗?

谢谢

【问题讨论】:

***.com/questions/3747448/… 或 ***.com/questions/9239240/… 【参考方案1】:

您正在制作一个不错的应用程序。我不太了解 smack,但我知道如何将对象从服务传递到 Activity。您可以为您的服务制作 AIDL。 AIDL 会将您的服务对象传递给活动。然后您可以更新您的活动 UI。这个link可能对你有帮助!

首先,您必须使用编辑器制作 .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 插件将在 gen/ 文件夹中自动生成 ObjectFromService2Activity 接口和存根。

Android SDK 还包括一个(命令行)编译器辅助工具(位于 tools/ 目录中),您可以使用它来生成 java 代码,以防您不使用 Eclipse。

在您的服务中覆盖 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。 More Help好玩!

【讨论】:

我还查看了广播接收器,因为它能够通过可序列化的额外内容通过 Intent 传递对象。有什么方法可以使用这种方法将对象传递给活动吗?你也有一些很好的aidl例子吗? 当您需要执行 IPC 时,为您的接口使用 Messenger 比使用 AIDL 实现它更简单,因为 Messenger 将所有对服务的调用排队,而纯 AIDL 接口会同时向服务发送请求,然后必须处理多线程。对于大多数应用程序,服务不需要执行多线程,因此使用 Messenger 允许服务一次处理一个调用。如果你的服务是多线程的很重要,那么你应该使用 AIDL 来定义你的接口。

以上是关于Android将自定义对象从服务传递给活动的主要内容,如果未能解决你的问题,请参考以下文章