我可以从 java.util.TimerTask::run() 运行 Activity 类方法吗?

发布于 2024-12-09 07:27:23 字数 496 浏览 0 评论 0 原文

在我的 Android 代码中,我通过调用 Timer.schedule(myTask,0,1000) 来响应按钮按下,它调用 myTimerTask::run(),如下所示:

嵌套在我的 Activity 中:

class mytimerTask extends TimerTask {
    @Override
    public void run() {
        //update my progress bar
        //if progress bar is full, i want to call a function that is in my activity
    }
}

Can I Straight up从 TimerTask 引用我的 Activity 方法之一?当我尝试时,应用程序似乎崩溃了。

对我来说,从 Runnable 而不是 Timer/TimerTask 处理我的 ProgressBar 和最终执行代码会更好吗?

Inside my Android code, I'm responding to a button press by calling Timer.schedule(myTask,0,1000), which calls myTimerTask::run(), which is something like this:

nested within my Activity:

class mytimerTask extends TimerTask {
    @Override
    public void run() {
        //update my progress bar
        //if progress bar is full, i want to call a function that is in my activity
    }
}

Can I straight up reference one of my Activity methods from TimerTask? It seems to crash the app when I try it.

Would it be better for me to handle my ProgressBar and eventual execution of code from a Runnable instead of a Timer/TimerTask?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

a√萤火虫的光℡ 2024-12-16 07:27:23

您需要按如下方式编写代码。要了解原因,请检查以下线程
什么是 Android UiThread(UI 线程)http://developer.android.com/resources/articles/painless-threading.html

   Timer t;
   Handler handler = new Handler();


t = new Timer();
Class MyTimerTask extends TimerTask{
    public void run() {
            handler.post(new Runnable() {
                    public void run() {
                        //update my progress bar
    //if progress bar is full, i want to call a function that is in my activity

                    }
           });
    }

    t.schedule(timeTask, 0, 1000);

You need to yor code as follow. To know reason check following thread
What is the Android UiThread (UI thread) or http://developer.android.com/resources/articles/painless-threading.html

   Timer t;
   Handler handler = new Handler();


t = new Timer();
Class MyTimerTask extends TimerTask{
    public void run() {
            handler.post(new Runnable() {
                    public void run() {
                        //update my progress bar
    //if progress bar is full, i want to call a function that is in my activity

                    }
           });
    }

    t.schedule(timeTask, 0, 1000);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文