Android 异步任务和取消

Android 异步任务和取消,android,asynchronous,Android,Asynchronous,我的应用程序就像一个启动器,当一个应用程序从我的应用程序中启动时,一个计时器就会启动,只允许你玩一段时间。但是,如果您返回到我的启动器,我希望计时器暂停,然后在您启动另一个应用程序后再次启动。我有以下资料: protected String doInBackground(String... strings) { while (playTime < ALLOWED_TIME) { try { Thread.sle

我的应用程序就像一个启动器,当一个应用程序从我的应用程序中启动时,一个计时器就会启动,只允许你玩一段时间。但是,如果您返回到我的启动器,我希望计时器暂停,然后在您启动另一个应用程序后再次启动。我有以下资料:

    protected String doInBackground(String... strings) {
        while (playTime < ALLOWED_TIME) {
            try {
                Thread.sleep(1000);
                long endTime = System.nanoTime() / Constants.NANO_SECONDS;
                int endTimeSec = (int) endTime;
                playTime = endTimeSec - START_TIME;

                if (stored.getBoolean("Foreground", false)) {
                    break;
                    cancel(true); //run this code if Arcade app is exited before time expires
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
受保护的字符串背景(字符串…字符串){
while(播放时间<允许的时间){
试一试{
睡眠(1000);
long-endTime=System.nanoTime()/Constants.NANO_SECONDS;
int endTimeSec=(int)endTime;
播放时间=结束时间秒-开始时间;
if(stored.getBoolean(“前台”,false)){
打破
取消(true);//如果Arcade应用程序在时间到期前退出,请运行此代码
}
}捕获(例外e){
e、 printStackTrace();
}
}
返回null;
}

编辑:请参阅答案,因为重新排序代码摘录是正确取消后台任务所必需的。

参考发布的代码,以下代码片段有效地取消后台线程和后台发生的关联循环:

if (true) {
    cancel(true); //this code cancels the background thread, breaks the loop therein
    break;
}

protected void onCancelled(){
    //anything to be run on main thread after cancellation
}

Toast Toast=Toast.makeText(上下文、错误、持续时间)Toast.show()
您正在更新ui,您应该会得到一个异常,因为您是从后台线程更新ui,这是不可能的,所以我只能在if{}中调用
cancel(true)
,然后在
onCancelled()
中执行所有其他操作。似乎一直存在的问题是if()的值从来都不是true,我想校对一些东西是个好主意,感谢这次更新,尽管Raghunandran说:您只能从UI线程创建Toast,就像在onProgressUpdate或onPostExecute中一样。还有其他方法可以在UI线程上运行它,但是从doInBackground来看,它不会显示出来。