nav*_*raj 6 service android asmack
我正在使用asmack为Android创建一个Instant Messenger.我已经启动了一个连接到xmpp服务器的聊天服务.该服务连接到xmpp服务器,我正在获得名册和存在.但现在我必须更新UI并将帐户对象列表从服务传递给活动.我遇到过Parcelable和可序列化的.我无法弄清楚这项服务的正确方法是什么.有些人可以提供一些代码示例,我也可以这样做.
谢谢
你正在制作一个不错的应用程序。我对 smack 不太了解,但我知道如何将对象从服务传递到 Activity。您可以为您的服务制作 AIDL。AIDL 会将您的服务对象传递给活动。然后您可以更新您的 Activity UI。此链接可能对您有帮助!
首先,您必须使用编辑器创建 .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();
}
Run Code Online (Sandbox Code Playgroud)
现在复制此文件并将其粘贴到您的项目文件夹中,ADT 插件将在 gen/ 文件夹中自动生成 ObjectFromService2Activity 接口和存根。
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()");
}
}
Run Code Online (Sandbox Code Playgroud)
使用您的 Activity 或您想要启动此服务并建立 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;
}
};
Run Code Online (Sandbox Code Playgroud)
使用 ObjectFromService2Activity 的对象,您可以访问方法 s1.getObjectFromService() 将返回 JSONObject。更多帮助乐趣!
| 归档时间: |
|
| 查看次数: |
5180 次 |
| 最近记录: |