繁体   English   中英

将服务中的JSON数据发送到Android中的UI

[英]Send JSON data from a service to UI in Android

要求是:我有一个后台服务,在该服务中,我正在执行REST调用以获取JSON数据。 我想将JSON数据发送到UI并更新内容。

我可以使用一种方法,即将整个JSON字符串存储在SharedPreferences中并在UI中进行检索,但我认为这样做并不高效。

有想法吗? 我在UI中添加了一个Handler来更新元素,但是我对使用它并不熟悉。

样本REST调用代码:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DATA_URL);

httpPost.setHeader("Content-Type", "application/json");

//passes the results to a string builder/entity
StringEntity se = null;
try {
    se = new StringEntity(RequestJSON.toString());
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

//sets the post request as the resulting string
httpPost.setEntity(se);

//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();

try {
    HttpResponse response = (HttpResponse) httpClient.execute(httpPost, responseHandler);

    // response will have JSON data that I need to update in UI

    //Show notification
    showNotification("Update Complete");



} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    // httpClient = null;
}

在UI活动中

Handler myHandler = new Handler() {



            @Override
            public void handleMessage(Message msg) {

                Bundle Recevied = msg.getData();
                String resp = Recevied.getString("Mkey");

            }
    };

    messenger = new Messenger(myHandler);


}

将信息传递给服务人员并准备好结果:

Message msg = Message.obtain();

Bundle data = new Bundle();
data.putString("Mkey",
        Smsg);
msg.setData(data);


try {
    // Send the Message back to the client Activity.
    messenger.send(msg);
} catch (RemoteException e) {
    e.printStackTrace();
}

像这样的东西可能适合您。 TL; DR:在更新活动的服务中创建一个侦听器。

在服务中,创建一个静态函数和一个静态字段:

private static BlaBlaService _instance;

public static BlaBlaService getInstance() {
    return _instance;
}

在onCreate函数上填充_instance字段:

public void onCreate() {
        super.onCreate();
       _instance = this;
      ...
}

public void addRESTCompleteListener(RESTCompleteListener l) {...}

REST调用完成后,调用:

listener.RESTCompleted(JSON.whatever)

现在,在您的活动中,只需在服务启动后将其添加到服务中即可:

BlaBlaService.getInstance().addRESTCompleteListener(listener)

不要忘记在需要时释放所有指针。

希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM