的Andr​​oid如何在其他类runOnUiThread? [英] Android how to runOnUiThread in other class?

查看:168
本文介绍了的Andr​​oid如何在其他类runOnUiThread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主要活动的应用程序有线程,它工作正常,但是当我调用其他类来得到服务器的数据我不能运行的线程....

 类MainActivity扩展活动实现Runnable {

    公共无效的onCreate(){
        新的主题(这一点)。开始();
    }

    公共无效的run(){
        //这里是code下载数据从服务器完成后,这和setData()方法在处理即时调用其他类....
    }

    公共无效使用setData();
    {
        新checkData(本);
    }
}

类checkData {

    公共无效checkdata(上下文的背景下){
        context.runUIonthread(){//着呼叫作为runUIthread ............
    }

}
 

解决方案

看文章沟通与UI线程

使用上下文在手,你可以在任何类中创建一个处理程序。否则,你可以叫 Looper.getMainLooper(),无论哪种方式,你得到的主UI线程。

例如:

 类checkData {
    私人最终处理程序处理;

    公共无效checkdata(上下文的背景下){
       处理程序=新的处理程序(context.getMainLooper());
    }

    公共无效的someMethod(){
       // 做工作
       runOnUiThread(新的Runnable(){
           @覆盖
           公共无效的run(){
               // code到UI线程上运行
           }
       });
    }

    私人无效runOnUiThread(Runnable的R){
       handler.post(r)的;
    }
}
 

In my application in Main Activity there is thread and it works fine but in when i call other class to get data from server i cant run thread ....

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 void checkdata(Context context){
        context.runUIonthread(){//cant call as runUIthread............
    }   

}

解决方案

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

这篇关于的Andr​​oid如何在其他类runOnUiThread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆