Search code examples
javaandroidmultithreadinghttp-requestloopj

Displaying Notification after Background Process done Android


I am loading an HTTP request in the background using loopj HTTP CLIENT and when it is done, I want to display a "success" notification (dialog, toast, etc.)

I have the code in a seperate (non-activity) class with a static method that executes the background request. In the end, the response is in a AsyncHttpResponseHandler under a onSuccess method. In this method, I can print out the response, confirm that the request went through, save data to the sd card/ Shared Preferences, but how do I access the UI thread to display a notification?

Thanks in advance.


Solution

  • you can do it using a Handler, or by calling Activity.runOnUiThread(). so you either pass a Handler, or an Activity object to your static method, then in your onSuccess() method, do,

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
          // i'm on the UI thread!
        }
      }
    );
    

    or,

    handler.post(new Runnable() {
        @Override
        public void run() {
          // i'm on the UI thread!
        }
      }
    );