其他分享
首页 > 其他分享> > 将服务中的JSON数据发送到Android中的UI

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

作者:互联网

要求是:我有一个后台服务,在该服务中,我正在执行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();
}

标签:android,json,rest,background-service
来源: https://codeday.me/bug/20191009/1883110.html