Android how to runOnUiThread in other class?

后端 未结 6 1952
再見小時候
再見小時候 2020-11-28 08:22

In my application, in MainActivity, there is a thread which works fine. But when I call another class to get data from the server I can\'t run on a thread. See code exampl

6条回答
  •  囚心锁ツ
    2020-11-28 09:19

    Activity is a class that extends Context. So there is no need to pass both context and activity. You may pass activity as context and then you can use the context to run on UI thread as follows:

    ((Activity) context).runOnUiThread(new Runnable() {
            public void run() {
                //Code goes here
            }
        });
    

    Word of Caution: Only use this when you're sure that context is an activity context, and it's not a good practice to assume that.

提交回复
热议问题