Send JSON data from a service to UI in Android

2019-02-20 18:38发布

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

2条回答
贼婆χ
2楼-- · 2019-02-20 19:01

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();
}
查看更多
淡お忘
3楼-- · 2019-02-20 19:05

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 :)

查看更多
登录 后发表回答