I am trying to update my UI in FirstActivity
when I receive a notification but is confused by runOnUiThread
, Runnable
and Handler
. Here is what I have: I am running FirstActivity and NotificationService. When NotificationService reeives a notification, it will update FirstActivity UI.
I also have another service AlarmService
running.
First Activity
@Override
public void onResume() {
super.onResume();
//some other code for alarm service
}
NotificationService
//on receiving notification
private void showNotification(String text) {
//Get activity
Class<?> activityClass = null;
try {
activityClass = Class.forName("com.pakage.FirstActivity");
contextActivity = (Activity) activityClass.newInstance();
//Update UI on FirstActivity not working
contextActivity.runOnUiThread(new Runnable() {
public void run()
{
Looper.prepare();
TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
Looper.loop();
}
});
} catch (Exception e) {
e.printStackTrace();
}
//Shows the notification
Notification n = new Notification();
//... etc
}
I keep getting looper.prepare error. Do I need to put extra codes in my FirstActivity?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.
Android Thread Updating the UI from a Background Thread The solution is to use the runOnUiThread() method, as it allows you to initiate code execution on the UI thread from a background Thread.
In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });
However, note that you cannot update the UI from any thread other than the UI thread or the "main" thread. To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: Activity.
My 1st instinct is that you should instead have the Activity bind to your service and handle the UI update on its side instead of the Service directly modifying the Activity.
See more info here:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
And an example here:
Example: Communication between Activity and Service using Messaging
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With