在服务中将JSON数据从服务发送到UI

时间:2014-10-29 13:52:20

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

在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();
}

答案 1 :(得分:0)

这样的东西可能适合你。 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)

不要忘记在需要时丢弃所有指针。

希望这会有所帮助:)