2012-05-23 28 views
3

我正在使用asmack为android创建Instant Messenger。 我已经开始了一个连接到xmpp服务器的聊天服务。 该服务连接到xmpp服务器,我正在获得名单和存在。 但现在我必须更新UI并将服务中的帐户对象列表传递给活动。我遇到了Parcelable和可序列化。 我无法弄清楚这项服务的正确方法。 有人可以提供一些代码示例,我可以做同样的事情。从服务到活动的Android Pass自定义对象

谢谢

+1

http://stackoverflow.com/questions/3747448/android-passing-data-between-service-and-activity 或 http://stackoverflow.com/questions/9239240/passing -object-through-intent-from-background-service-to-an-activity –

回答

1

你正在做一个不错的应用程序。我不知道更多关于smack的知识,但我知道如何将对象从服务传递给Activity。您可以为您的服务制作AIDL。 AIDL会将您的服务对象传递给活动。然后你可以更新你的Activity 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插件会自动生成在根/文件夹中的ObjectFromService2Activity接口和存根。

Android SDK还包括一个(命令行)编译器aidl(在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好玩!

+0

感谢您的帮助vajaparvin。 – navraj

+0

我也看了一下broadcastreciever,因为它能够通过Intent通过可序列化的附加方式传递对象。有什么办法可以用这种方法将对象传递给活动?你也有一些很好的例子吗? – navraj

+0

当您需要执行IPC时,使用Messenger作为接口比使用AIDL实现它更简单,因为Messenger将所有调用排队到服务,而纯AIDL接口同时向服务发送请求,然后服务必须处理多线程,穿线。 对于大多数应用程序,该服务不需要执行多线程,因此使用Messenger可以让该服务一次处理一个呼叫。如果你的服务多线程化很重要,那么你应该使用AIDL来定义你的接口。 – Mahesh