0

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;
}
Sumit Sahoo
  • 2,949
  • 1
  • 25
  • 37
  • 1
    Please post your code first ! – S.Thiongane Oct 29 '14 at 13:53
  • Added REST call code – Sumit Sahoo Oct 29 '14 at 14:02
  • You need to learn about Intents: http://developer.android.com/guide/components/intents-filters.html Data like a JSON string or mapped objects can be attached and the receiving e.g. `Activity` can use it. Also, you can bind an activity to a service and interact with it when your app is open. – Blacklight Oct 29 '14 at 14:06
  • Create a messanger in UI activity and pass it to service one process done send data to UI activity through messanger.. – H4SN Oct 29 '14 at 14:19

2 Answers2

1

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

Protostome
  • 5,569
  • 5
  • 30
  • 45
  • I have a timer code inside Service that keeps on invoking the REST call based on a specified duration and based on that I want to update the UI. `private void performRepeatedTask() { timer.scheduleAtFixedRate(new TimerTask() { public void run() { mLocationClient.connect(); } }, 0, UPDATE_INTERVAL); }` – Sumit Sahoo Oct 29 '14 at 14:41
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();
}
H4SN
  • 1,482
  • 3
  • 24
  • 43
  • I saw the implementation of Message before, can I add a JSON object as message ? Well if that is not possible we can always make the entire JSON as string and send right ? – Sumit Sahoo Oct 29 '14 at 14:37
  • 1
    yes you can send JSON string or you can also use Gson library which can convert an object to string and in main thread you can construct object again. – H4SN Oct 29 '14 at 14:42
  • So basically I will have to add `messenger.send(msg);` once the REST call is finished and in UI listen for handleMessage and call my updateUI method. Did I get that correctly ? – Sumit Sahoo Oct 29 '14 at 14:45
  • yes! on UI you will get your required data to update ui – H4SN Oct 29 '14 at 15:05