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