Updating UI from a service (using a handler?)
Solution 1
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
Solution 2
I've always just had the service fire off a Broadcast and then in my Activity I have a BroadcastReciever listening for the Broadcast. It's an approach that is much simpler than the one you outlined above.
Comments
-
newbie over 4 years
I am trying to update my UI in
FirstActivity
when I receive a notification but is confused byrunOnUiThread
,Runnable
andHandler
. 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?
-
Alan Moore over 12 yearscan you show us the messages in your log from logcat? Also, how did you declare Looper?
-
newbie over 12 yearsI am getting
Can't create handler inside thread that has not called Looper.prepare()
error. Looper is declared in theshowNotification
method above -
Davide Cannizzo about 6 yearsYou're getting that error because you're running your code on the UI thread, which already owns a Looper lifecycle. To avoid that error, you could just remove
Looper.prepare()
, but it makes a non-sense since `Looper.loop()' would block the whole thread and the UI of your app would neither work nor respond anymore!
-
-
newbie over 12 yearsBoth the service and activity are running in the same process. What do you mean by saving a reference to the activity? I tried using
FirstActivity.runOnUiThread
.