0
我的應用程序像啓動程序一樣工作,當應用程序從我的應用程序中啓動時,計時器啓動,只允許您玩一段時間。但是,如果您返回到我的啓動器,我希望計時器暫停,然後在啓動另一個應用後再次啓動。我有以下幾點:AsyncTasks和取消
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;
}
編輯:見的答案,因爲它原來的重新排序代碼摘錄是要正確取消後臺任務。
'吐司吐司= Toast.makeText(上下文,錯誤持續時間)toast.show ()'你正在更新ui你應該得到一個異常因爲你正在從後臺線程更新ui是不可能的 – Raghunandan
所以我只在我的if {}中調用'cancel(true)',然後在'onCancelled中做所有其他的東西()'。似乎持續存在的問題是if()從來沒有真值,我想校對一些東西是一個好主意,感謝這次更新,儘管 – mike
Raghunandran說:你只能從UI線程創建一個Toast,如onProgressUpdate或onPostExecute。還有其他方法可以在UI線程上運行它,但是從doInBackground中它不會顯示。 – Christine