任务在asynctask中完成后显示进度对话框

时间:2013-01-21 19:30:31

标签: android android-asynctask progressdialog telnet

您好我想显示progressdialog,直到通过telnet执行命令。 所以我为此目的使用asynctask

private class AsyncAction extends AsyncTask<String, Void, String> 
{

    @Override
    protected String doInBackground(String... arg0) 
    {
        // TODO Auto-generated method stub


        return null;
    }

    @Override
    protected void onPostExecute(String result) 
    {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        try
          {

              telnet.connect("XXX.XXX.XXX.XXX", 23);

                // Get input and output stream references
                in = telnet.getInputStream();
                out = new PrintStream(telnet.getOutputStream());

                // Log the user on
                readUntil("login:");
                write("jk");
                readUntil("password:");
                write("kk");

                // Advance to a prompt
                readUntil(prompt + "");
                write("ping -t localhost\n");
                readUntil(">");
                write("cdkk");


                AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
                String msg="work finished!";
                alertbox.setMessage(msg);
                alertbox.show();

        } 
          catch (Exception e) 
          {
            // TODO: handle exception
        }
        finally
        {
            pd.dismiss();
        }





//          pd.dismiss();
    }

    @Override
    protected void onPreExecute() 
    {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pd = new ProgressDialog(TelSampActivity.this);
        pd.setMessage("loading...");
        pd.setIndeterminate(true);
        pd.setCancelable(false);
        pd.show();
    }

}

我在asynctask中拨打oncreate(),如下所示

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try{   

         new AsyncAction().execute();

        }catch (Exception e) {
            e.printStackTrace();
        }

}

问题是在命令执行之前我看不到progressdialog。 请帮我解决问题。 提前谢谢。

修改

发送和读取命令的代码

public String readUntil(String pattern) {
    try {
    char lastChar = pattern.charAt(pattern.length()-1);
    StringBuffer sb = new StringBuffer();
    boolean found = false;
    char ch = (char) in.read();
    while (true) {
    System.out.print(ch);
    sb.append(ch);
if (ch == lastChar) 
{
if (sb.toString().endsWith(pattern)) 
{
    if (sb.toString().contains("cdkk"))
    {
        disconnect();
        break;


    }
    else
    {
        return sb.toString();
    }

}
else
{
    disconnect();
    break;
}
}
else if(sb.toString().contains("Failed"))
{
    AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
        String error="Invalid username or password!";
        alertbox.setMessage(error);
        alertbox.setTitle("Error");
        alertbox.show();
    System.out.println("bad user name");
    disconnect();
    break;
}

ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}

public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}

3 个答案:

答案 0 :(得分:1)

目前,您正在尝试从onPostExecute执行网络操作,因为此方法是从UI线程调用的。改变你的代码以正确的方式工作

private class AsyncAction extends AsyncTask<String, Void, String> 
{
     public static boolean status=false;
    @Override
    protected String doInBackground(String... arg0) 
    {
        // TODO Auto-generated method stub
        try
          {

              telnet.connect("XXX.XXX.XXX.XXX", 23);

                // Get input and output stream references
                in = telnet.getInputStream();
                out = new PrintStream(telnet.getOutputStream());

                // Log the user on
                readUntil("login:");
                write("jk");
                readUntil("password:");
                write("kk");

                // Advance to a prompt
                readUntil(prompt + "");
                write("ping -t localhost\n");
                readUntil(">");
                write("cdkk");
               // make status true or false if command successfully executed 
              status=true;

        } 
          catch (Exception e) 
          {
            // TODO: handle exception
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) 
    {

       pd.dismiss();
         // check status if true then show AlertDialog
      if(status==true){
       AlertDialog.Builder alertbox = 
                        new AlertDialog.Builder(TelSampActivity.this);
       String msg="work finished!";
       alertbox.setMessage(msg);
       alertbox.show();
     }
    else{
           // your code here
       }

    }

    @Override
    protected void onPreExecute() 
    {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pd = new ProgressDialog(TelSampActivity.this);
        pd.setMessage("loading...");
        pd.setIndeterminate(true);
        pd.setCancelable(false);
        pd.show();
    }

}

答案 1 :(得分:0)

你需要在onPreExecute()中显示进度条,在doInBackground()中执行工作,然后在onPostExecute()中隐藏进度条。 onPreExecute()和onPostExecute()都在主线程上执行,其中doInBackground在后台执行。

答案 2 :(得分:0)

您正在使用 onPostExecute()方法进行工作,该方法应该在 doInBackground()内部 在 onPreExecute()中显示进度对话框,并在 onPostExecute()中关闭。