Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

multithreading - Android how to runOnUiThread in other class?

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 example below.

class MainActivity extends Activity implements Runnable {

    public void onCreate() {
        new Thread(this).start();
    }

    public void run() {
        //here is code for download data from server after completion this and in handler  i m call other class in setdata() method....
    }

    public void setData() {
        new CheckData(this);
    }
}

class CheckData {
    public CheckData(Context context) {
        context.runUIonthread(){//cant call as runUIthread............
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See the article Communicating with the UI Thread.

With Context in hand, you can create a Handler in any class. Otherwise, you can call Looper.getMainLooper(), either way, you get the Main UI thread.

For example:

class CheckData{
    private final Handler handler;

    public Checkdata(Context context){
       handler = new Handler(context.getMainLooper());
    } 

    public void someMethod() {
       // Do work
       runOnUiThread(new Runnable() {
           @Override
           public void run() {
               // Code to run on UI thread
           }
       });
    }

    private void runOnUiThread(Runnable r) {
       handler.post(r);
    }  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...