Android FTP下载进度条

时间:2014-05-23 16:45:39

标签: java android ftp android-asynctask

FTP代码,但只有下载...

public class ImageUploadTask extends AsyncTask <String, Void, String>{
String e;


protected String doInBackground(String...args) {
    String strResponce = "";
    ftpClient = new FTPClient();
    s="finish";
    try {

        ftpClient.connect(InetAddress.getByName(SERVER));
        ftpClient.login(USERNAME, PASSWORD);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        textTargetUri.setText("good");


        final String remote = "/1.jpg";//FTP adress/filename
        String savefilepath = "/sdcard/download"+remote;
        File downloadfile = new File(savefilepath);//download

        local = new FileOutputStream(downloadfile);

        ftpClient.retrieveFile(remote, local);

        local.close();
        ftpClient.disconnect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{

    }
    return s;
}
}

BUT !! FTP下载代码执行插入CountingOutputStream功能。 CountingOutputStream函数为commons-io-2.4.jar。 项目位于commons-io-2.4.jarcommons-net-3.3.jar。 T_T

public class ImageUploadTask extends AsyncTask <String, Void, String>{
String e;


protected String doInBackground(String...args) {
    String strResponce = "";
    ftpClient = new FTPClient();
    s="finish";
    try {

        ftpClient.connect(InetAddress.getByName(SERVER));
        ftpClient.login(USERNAME, PASSWORD);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        textTargetUri.setText("good");

        final String remote = "/1.jpg";//FTP adress/filename
        String savefilepath = "/sdcard/download"+remote;
        File downloadfile = new File(savefilepath);//download

        local = new FileOutputStream(downloadfile);
        long fileSize = 0;
        FTPFile[] files = ftpClient.listFiles(remote);
        if (files.length == 1 && files[0].isFile()) {
            fileSize = files[0].getSize();

            String a = String.valueOf(fileSize);
            Log.d("File Size", a);

        }

        CountingOutputStream cos = new CountingOutputStream(local) {
              protected void beforeWrite(int n) {
                      super.beforeWrite(n);

                      int progress = Math.round((getCount() * 100) / 879394);
                      //String b = String.valueOf(progress);
                      //Log.d("File persent", b);

              }
        };
        ftpClient.retrieveFile(remote, cos);

        local.close();
        ftpClient.disconnect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally{

    }
    return s;
}


    }

代码有什么问题,我不知道怎么办?

代码没有错误。

但APP启动错误。

1 个答案:

答案 0 :(得分:0)

在后台(例如doInBackGround())中,根本不能更改UI元素。如果在活动中使用 runOnUiThread ,或者使用 textTargetUri.post 。这样,setText部分就会根据需要在UI线程上进行。