异步任务在后台加载,但无法在Android中显示

时间:2013-10-30 11:43:58

标签: java android android-asynctask

我有以下代码 -

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.widget.Toast;

public class MyClass extends Activity 
{
private static final int SLEEP_TIME= 30*10; 
    //that corresponds to ~30sec 

Button mbtn;
String ipa[]=new String[10];
MyTask objMyTask;

//intialise some 10 IP Adrresses
//intialise other required variables

protected void onCreate(Bundle savedInstanceState)
 {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mbtn = (Button)findViewById(R.id.my_btn);

    mbtn.setOnClickListener(new View.OnClickListener()
      {
        public void onClick(View v) 
         {

        objMyTask = new MyTask();
        objMyTask.execute();

        // (*) At this point loop starts to run 
        & Async task starts executing, but it fails to 
       display till the loop ends, although it runs

        // FOR LOOP 1

         for(int c=1; c<=10; c++)
          { 

           String rec1 = ping(ipa[c]); 

           if( some condition involving rec1 )
           {

            Toast.makeText(getApplicationContext(), 
            " Ping Successfull ", Toast.LENGTH_LONG).show();
            }

           else
           {

            Toast.makeText(getApplicationContext(),
            " Pinging Failed ", Toast.LENGTH_LONG).show();
            }
               }
         }

      }
   );
     }

public String ping(String ip_addrs) 
{   


 //code to check whether ip_addrs is reachable

       return str;

    }

class MyTask extends AsyncTask<Void, Integer, Void> {

    Dialog dialog;
    ProgressBar progressBar;
    TextView tvLoading,tvPer;
    Button btnCancel;


    @Override
    protected void onPreExecute() 
      {
        super.onPreExecute();
        dialog = new Dialog(Display.this);
        dialog.setCancelable(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.progressdialog);
        progressBar = (ProgressBar) dialog.findViewById(R.id.progressBar1);
        // inherit other components


        btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                objMyTask.cancel(true);
                dialog.dismiss();
            }
        });

        dialog.show();
      }

    @Override
    protected Void doInBackground(Void... params)
         {


        //FOR LOOP 2
        for (int i = 1; i <100; i++) {
            if (isCancelled()) {
                break;
            } else {
                //System.out.println(i);
                publishProgress(i);
                try {
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
      }

    @Override
    protected void onProgressUpdate(Integer... values) 
             {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
        tvLoading.setText("Loading...  " + values[0] + " %");
        tvPer.setText(values[0]+" %");

     }

    @Override
    protected void onPostExecute(Void result)
             {

        super.onPostExecute(result);

        dialog.dismiss();

        AlertDialog alert = new AlertDialog.Builder(Display.this)
                .create();

        alert.setTitle("Completed!!!");
        alert.setMessage("Your Task is Completed SuccessFully!!!");
        alert.setButton("Dismiss", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        alert.show();
        }
          }
  }   //End of main class

P.S:假设完成整个For循环1需要~10秒。

(*) 当我运行此代码时,Fisrt 10秒手机仍然冻结,从第11秒开始第二个进度条开始显示到第30秒,此时,Prg.Bar已经覆盖了33%(即10秒)

那么,为什么Progress Bar不会“显示”(虽然它会运行)很快就会被执行,但是在循环完成后就会开始显示。(另请注意,即使是10秒后显示的祝酒词) )。

请有人告诉我这段代码有什么问题,我哪里出错了,以及如何纠正让for循环1运行时同步显示ProgressBar

非常感谢任何帮助。

0 个答案:

没有答案