Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...