Updating UI from a service (using a handler?)

前端 未结 3 542
谎友^
谎友^ 2020-12-11 06:12

I am trying to update my UI in FirstActivity when I receive a notification but is confused by runOnUiThread , Runnable and Handl

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 07:00

    I have no idea why you are putting a Looper in

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

    because the UI (main) thread already has a Looper/Handler etc..

    Even if it did work Looper.loop() is going to block and since you are running it on the UI thread, it will block the UI thread which is not what you want.

    What you really want to do is

    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
        }
    });
    

    You don't really need to do all this fancy stuff to get the Activity

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

    assuming the Service and Activity are both running in the same process you can just save a reference to the Activity but be careful to update the reference when the Activity gets destroyed.

提交回复
热议问题