在我的一项活动中,我正在使用AsyncTask
。在doInBackground()
中,我正在调用各种方法。在这些方法之一中,我遇到了异常,因此在catch块中,我想在Toast中显示错误。我知道我可以使用Log
,但我仍然更喜欢Toast。因此,如何在doInBackground()的AsyncTask中使用Toast?
您可以将Toast包装在runOnUIThread()
中,但这不是最佳解决方案。发生错误时,应在catch块中设置一个布尔标志,然后在runOnUIThread()
,onProgressUpdate()
或任何其他具有UI访问权限的方法中,只要该标志为onPostExecute()
,就显示适当的Toast。
从doInBackground返回为
true
在protected String doInBackground(String... params){
//some code
try{
//some code
}catch(Exception e){
return "Exception Caught";
}
return someValidResult;
}
protected void onPostExecute(String result){
if(result.equalsIgnoreCase("Exception Caught")){
//Display Toast
}else{
// // whatever you wana do with valid result
}
}
方法中,在必须显示吐司的地方编写以下代码
doInBackground()
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();
}
});
,则需要通过活动呼叫Fragments
:runOnUiThread(...)
您可以在可以访问UI线程的方法中显示它,例如getActivity().runOnUiThread(...)
,onPreExecute()
和onProgressUpdate()
创建处理程序对象并使用该对象执行所有Toast消息。
onPostExecute()
@Override
protected Void doInBackground(Void... params) {
Handler handler=new handler();
handler= new Handler(context.getMainLooper());
handler.post( new Runnable(){
public void run(){
Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show();
}
});
}
可以很好地在doInBackground()方法中显示烤面包
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();
}
});
尝试此代码
activity.runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(activity, "Toast teaxt", Toast.LENGTH_SHORT).show();
}
});
如果必须声明与Thread相关的任何东西,那么它必须在runOnUiThread()方法之外,然后才将要执行,
void showError(final String err) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(downloadprogress.this, err + "error in download", Toast.LENGTH_LONG)
.show();
}
});
}