android - 异步任务、进度条和 I/O

标签 android io android-asynctask ping android-progressbar

我很抱歉发布了与上一个类似的问题,但我就是无法弄清楚这一点。

我一直在使用简单的“ping”示例,我发现here只是想添加 ProgressBar 但没有运气。我真的不明白发生了什么事。

所以,这工作正常:

    protected void onPreExecute() {
    sb = new StringBuilder();
    mPOut = new PipedOutputStream();
    try {
        mPIn = new PipedInputStream(mPOut);
        mReader = new LineNumberReader(new InputStreamReader(mPIn));
    } catch (IOException e) {
        cancel(true);
    }
    //myBar.setVisibility(View.VISIBLE); -> PROBLEM!!!
}

protected Object doInBackground(Object... arg0) {
    try {
        process = Runtime.getRuntime().exec("ping -c 4 " + ipadd);
        InputStream in = process.getInputStream();
        OutputStream out = process.getOutputStream();
        byte[] buffer = new byte[1024];
        int count;
        while ((count = in.read(buffer)) != -1) {
            mPOut.write(buffer, 0, count);
            String bs= new String(buffer);
            publishProgress(); 
        }
        in.close();
        out.close();
        mPOut.close();
        mPIn.close();
    } catch (IOException e) {
    }
    return null;
}

protected void onPostExecute(Object result) {
            myBar.setVisibility(View.INVISIBLE);
            tv.setText(sb);
            System.out.println(sb);
}

我从 ping 中得到输出,myBar 显然没有显示,因为它首先是不可见的。

如果我从标记为问题的行中删除注释(将进度条可见性设置为可见),我将无法从 ping 中获得任何输出。我似乎它以某种方式搞乱了我的 I/O 之类的东西。 ProgressBar显示,最后隐藏,但没有输出。

我真的无法弄清楚这一点,所以如果您有任何想法,我将非常感谢您的帮助。

谢谢!!!

最佳答案

尝试在 OnPreExecute() 方法中以编程方式创建 ProgressDialog,并在 onPostExecute() 中完成任务后将其关闭。这是一个代码:

add to onPreExcute:
    super.onPreExecute();
    ProgressDialog pDialog = new ProgressDialog(YourActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

add to onPostExecute:
   pDialog.dismiss();

关于android - 异步任务、进度条和 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12235277/

相关文章:

android - 在内部存储中保存和获取图像 url

使用 inpout32.dll 的 Java I/O

C++:如何让动态数组的索引由文件中的行确定

java - Android 从 AsyncTask 访问 MainActivity

Android:不显示对话框的Asynctask

android - Android中EditText的InputType

android - Unicode 符号无法在移动设备中正确显示

android - 如何从 AlertDialog 获取 View ?

c# - 使用 Shell Execute 重定向标准输出

java - 用于 Fragment 的 AsyncTask 结果