在我的Android应用程序中,我正在花费大量时间来扩展AsyncTask,并希望在Toast消息中显示进度。 Toast消息也显示在Pre()和onPost()上。
我可以在Pre()&上显示Toast消息。 onPost()但无法显示onProgressUpdate(整数...进度)。
以下是我的代码......
public class MainClass extends Activity {
public void Start(View view) {
DemoTasks runner = new DemoTasks(this);
runner.execute("Start");
}
private class DemoTasks extends AsyncTask<String, Integer, Integer> {
private Context context;
public DemoTasks(Context context){
this.context = context;
}
@Override
protected Integer doInBackground(String... params) {
try {
publishProgress(0);
doWork();
Thread.sleep(5000L);
publishProgress(100);
} catch (Exception localException) {
Log.d("POST", localException.getMessage());
}
return 100;
}
@Override
protected void onPostExecute(Integer result) {
Toast.makeText(context, "post", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPreExecute() {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(context, "progress-" + progress, Toast.LENGTH_SHORT).show();
}
}
}
同样在我的doInBackgroud(String ... params)中...... Thread.sleep也无效。 一旦onPre()被执行,onPost()也会在执行之后执行!!!!
答案 0 :(得分:0)
你可以试试这个,
showProgress ();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
dialog.cancel();
Intent i=new Intent(getApplicationContext(),Main.class);
startActivity(i);
finish();
}
}, 3000); //number of seconds
private ProgressDialog dialog;
public void showProgress () {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Please wait");
dialog.show();}
最重要的是,您可以使用任何方法访问用户界面,即使在doinBackground
中,您也可以使用runOnUIthread
访问用户界面。
答案 1 :(得分:0)
这是一个AsyncTask示例。这将在执行任务时显示一个进度对话框。
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
progressDialog.setMax(100);
progressDialog.setMessage("Please Wait..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.show();
}
protected void onPreExecute (){
}
@Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
@Override
protected void onProgressUpdate(Long... progress) {
// int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
progressDialog.setProgress(progress);
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
您可以将此任务称为
new LoginProcessing(loginCredentials).execute();
在此示例中 loginCredentials 是我传递给AsyncTask的参数。您可以将其更改为您自己的参数。