ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-10-10 00:37:01  阅读:189  来源: 互联网

标签:android json rest background-service


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有