Send JSON data from a service to UI in Android

陌路散爱 提交于 2019-12-30 14:17:21

问题


The requirement is : I have a background service and in that service I am doing a REST call to get a JSON data. I want to send the JSON data to UI and update contents.

One method I can use i.e. store the entire JSON string in SharedPreferences and retrieve in UI but I don't think that's efficient.

Any idea guys ? I have added a Handler in UI to update elements but I am not that familiar in using it.

Sample REST call code :

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;
}

回答1:


On UI activity

Handler myHandler = new Handler() {



            @Override
            public void handleMessage(Message msg) {

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

            }
    };

    messenger = new Messenger(myHandler);


}

pass the messanger to service and once result ready:

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



回答2:


Something like that may be suitable for you. TL;DR: Create a listener in the service that updates the activity.

In the service, make a static function and a static field:

private static BlaBlaService _instance;

public static BlaBlaService getInstance() {
    return _instance;
}

Populate the _instance field on the onCreate function:

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

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

Once a REST call is complete call:

listener.RESTCompleted(JSON.whatever)

Now in your activity, simply add the listener to the service once it starts:

BlaBlaService.getInstance().addRESTCompleteListener(listener)

Don't forget to dispose all the pointers when needed.

Hope this helps :)



来源:https://stackoverflow.com/questions/26632134/send-json-data-from-a-service-to-ui-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!