Android TimerTask throws RuntimeException if Show ProgressDialog is added in run()

喜你入骨 提交于 2019-12-11 12:15:54

问题


I am trying to schedule a timer using the timertask. I want to freeze the UI when the task is running using the ProgressDialog. I am using AsyncTask with TimerTask to achieve the desired results. But when I add Progress Dialog code to TimerTask Runnable, it throws Runtime Exception. Below is the code for TimerTask, Any help would be appreciated. Thanks in advance.

public class MyTimerTask extends TimerTask { Context contxt; public MyTimerTask(Context cn){ contxt=cn;

}
public void run() { 
try { 

pd=ProgressDialog.show(contxt, "Searching For Records", "Please wait...", true, true);

 reqtype="GO";
 _getRecords=new InitTask();
 _getRecords.execute(contxt);

} catch (Exception e) { 
Log.e(">>>>>>>>>>>> Error executing MyAsyncTask: ", e.getMessage(), e); 
} 
} 
} 

回答1:


That probably happens because you are attempting to use GUI features in a nonGUI thread. Have a look at http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29 for a possible fix.



来源:https://stackoverflow.com/questions/4573711/android-timertask-throws-runtimeexception-if-show-progressdialog-is-added-in-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!