Search code examples
androidjsonrestbackground-service

Send JSON data from a service to UI in Android


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

Solution

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