在Main和AsyncTask中使用相同的代码会产生不同的结果

时间:2013-09-04 16:33:01

标签: java android android-asynctask bufferedreader

我试图使用以下代码获取下载进度:

Java程序代码:

URLConnection conn = null;
URL url = null;
try {
    url = new URL("http://stackoverflow.com");
    conn = url.openConnection();
    conn.connect();
    InputStream in = new BufferedInputStream(url.openStream());
    int fileSize = conn.getContentLength();
    System.out.println("File size " + fileSize);
    int count;
    int i=0;
    while ((count = in.read()) != -1) {
        i++;
        if(i%50000==0){//Prints the decimal percentage every 50000 bytes
            System.out.println(((double)i)/((double)fileSize));
        }
    }
    in.close();
    System.out.println("Read " + i + " bytes of a possible " + fileSize);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

当我在Java应用程序的Main中尝试相同的代码时,我得到(几乎)正确的输出:

  

读取可能的191174的191202个字节

现在,如果我尝试将其整合到Android应用的AsyncTask中,请使用AsyncTask doInBackground()中的完全相同的代码并在AsyncTask中调用onCreate() {1}}(如下所示)我得到了结果

  

读取可能16983的156846个字节

因此,不仅android中的文件大小错误,而且读入的字节数也不同吗?我下载相同的文件,得到完全不同的结果。我已经多次运行并且两者都给出了大致相同的结果(stackoverflow的大小变化非常小但只有大约+/- 5000字节)。有人可以解释一下并帮我解决这个问题吗?

Android代码:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new LoadData().execute();
    }

    private class LoadData extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... params) {
            URLConnection conn = null;
            URL url = null;
            try {
                url = new URL("http://stackoverflow.com");
                conn = url.openConnection();
                conn.connect();
                InputStream in = new BufferedInputStream(url.openStream());
                int fileSize = conn.getContentLength();
                System.out.println("File size " + fileSize);
                int count;
                int i=0;
                while ((count = in.read()) != -1) {
                    i++;
                    if(i%50000==0){//Prints the decimal percentage every 50000 bytes
                        System.out.println(((double)i)/((double)fileSize));
                    }
                }
                in.close();
                System.out.println("Read " + i + " bytes of a possible " + fileSize);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

0 个答案:

没有答案