在单独的类上执行runOnUiThread [英] executing runOnUiThread on a separate class

查看:347
本文介绍了在单独的类上执行runOnUiThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Android如何在其他类中运行OnUiThread?

My Asyn Classes是一个单独的类文件。

My Asyn Classes are a separate class file.

public class AdamTask extends AsyncTask<String, Void, String>{
         public void showToast(final String toast)
        {
            runOnUiThread(new Runnable() {
                public void run()
                {
                    Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
                }
            });
        }
}

我如何在AsyncTask类中执行此方法?我收到错误方法 runOnUiThread(new Runnable(){})未定义类型AdamTask

How would I execute this method in my AsyncTask Class? I am getting an error The method runOnUiThread(new Runnable(){}) is undefined for the type AdamTask

新的AdamTask(Eve.this,如何在这里传递前夕活动)。执行();

new AdamTask(Eve.this, How to pass the eve activity here).execute();

推荐答案

你需要有活动的参考(让它命名为活动)并传递它到您的 AsyncTask 类。然后你可以这样调用 runOnUiThread

You need to have the Activity's reference (lets name it activity) and pass it to your AsyncTask class. Then you can call runOnUiThread like this:

activity.runOnUiThread

runOnUiThread 是在活动类中定义的方法。

The runOnUiThread is a method defined in Activity class.

只需在AsyncTask中添加一个contsructor即可。您的AsyncTask将如下所示:

Just add a contsructor to your AsyncTask. Your AsyncTask will look like this:

public class AdamTask extends AsyncTask<String, Void, String> {

private Activity activity; //activity is defined as a global variable in your AsyncTask

public AdamTask(Activity activity) {

    this.activity = activity;
}

public void showToast(final String toast)
    {
        activity.runOnUiThread(new Runnable() {
            public void run()
            {
                Toast.makeText(activity, toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

...

}

然后调用 AsyncTask 你需要这样的东西:

Then to call the AsyncTask you need something like this:

AdamTask adamTask = new AdamTask(Eve.this);
adamTask.excecute(yourParams);

更新正如Sam在评论中提到的,发生配置更改时,AsyncTasks 可能会导致上下文泄漏(一个示例是屏幕旋转时,活动被重新创建)。解决这个问题的方法是无头片段技术

UPDATE As Sam mentioned in the comments, AsyncTasks may result in context leaking when configuration changes occur (one example is when screen rotates and the Activity is recreated). A way to deal with this is the headless fragment technique.

另一种更高效的方法是使用事件总线。有关详细信息,请参阅此处(链接由山姆在评论中)。

Another way, more efficient, is using an event bus. See here for more information (link provided by Sam in the comments).

这篇关于在单独的类上执行runOnUiThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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