Updating the user interface from a service (using a handler?)

I am trying to update my user interface in FirstActivitywhen I receive a notification, but it is confused runOnUiThread, Runnableand Handler. Here is what I have: I run FirstActivity and NotificationService. When the NotificationService re-receives the notification, it will update the FirstActivity interface.

I also have another service AlarmService. 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 get looper.prepare error. Do I need to enter additional codes in my FirstActivity?

+5
source share
3 answers

, BroadcastReciever, . , , , .

+5

, Looper

contextActivity.runOnUiThread(new Runnable() {
    public void run()
    { 
        Looper.prepare();
        TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
        Looper.loop();

    }
});

UI () Looper/Handler ..

Looper.loop() , , , .

,

contextActivity.runOnUiThread(new Runnable() {
    public void run()
    { 
        TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
        tv.setText("do something that must be on UI thread") // or whatever
    }
});

,

activityClass = Class.forName("com.pakage.FirstActivity");
contextActivity = (Activity) activityClass.newInstance();

, , Activity, , , .

0

All Articles