java 从片段在 ui 线程上运行任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25743290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:36:02  来源:igfitidea点击:

run a task on ui thread from fragment

javaandroidmultithreading

提问by Hemant Shori

how to run a task on ui thread. I am trying to run a task on ui thread

如何在 ui 线程上运行任务。我正在尝试在 ui 线程上运行任务

  MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, 
                        "Mytask finished", 
                        Toast.LENGTH_SHORT).show();
                }
            });

回答by Hemant Shori

i found the solution for running task on ui thread in the fragment activity just change the MainActivity.this to getActivity() that will fix the error. i think this might help.

我找到了在片段活动中在 ui 线程上运行任务的解决方案,只需将 MainActivity.this 更改为 getActivity() 即可修复错误。我认为这可能会有所帮助。

Thread timer = new Thread() {
                @Override
                public void run() {
//do something
     getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(),
                            "Token Generated", Toast.LENGTH_SHORT).show();
                        }
                    });
       }
            };
            timer.start();