как показать индикатор прогресса загрузки FTP для Android - PullRequest
1 голос
/ 13 июня 2019

Я пытаюсь загрузить файл apk для обновления моего приложения, и файл apk помещен на ftp-сервер, и я загружаю этот apk с помощью FTP-клиента.

Даже если я звоню mProgress.setProgress(percent); ProgressBar не обновляется функцией, из которой я загружаю файл apk по ftp

public class UpdateAppByFTP extends AsyncTask<String,Void,Void> {
private Context context;
CopyStreamAdapter streamListener;
public void setContext(Context mContext){
    context = mContext;
}
private ProgressDialog mProgress;
@Override
protected void onPreExecute(){
    super.onPreExecute();
    mProgress = new ProgressDialog(this.context);
    mProgress.setMessage("Downloading new apk .. Please wait...");
    mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    //mProgress.setIndeterminate(true);
    mProgress.show();
}
@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    mProgress.dismiss(); //Dismiss the above Dialogue
}
@Override
protected Void doInBackground(String... arg0) {
    try {
        String serverName       = arg0[0];
        String userName         = arg0[1];
        String password         = arg0[2];
        String serverFilePath   = arg0[3];
        String localFilePath    = arg0[4];            if(getFileByFTP(serverName,userName,password,serverFilePath,localFilePath)){
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(localFilePath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);
        }else{
            //Do nothing could not download
        }
        String apkLocation="/download/"+"SmartPOS.apk";
        Intent intent1 = new Intent(Intent.ACTION_VIEW);
        intent1.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() +apkLocation)), "application/vnd.android.package-archive");
        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
        context.startActivity(intent1);
    } catch (Exception e) {
    }
    return null;
}
//Below code to download using FTP
public  boolean getFileByFTP(String serverName, String userName,
                                   String password, String serverFilePath, String localFilePath)
        throws Exception {
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(serverName);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return false;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                throw e;
            }
        }
        throw e;
    } catch (Exception e) {
        throw e;
    }
    try {
        if (!ftp.login(userName, password)) {
            ftp.logout();
        }
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        final int lenghtOfFile =(int)getFileSize(ftp,serverFilePath); 
        OutputStream output = new FileOutputStream(localFilePath);
        CountingOutputStream cos = new CountingOutputStream(output) {
            protected void beforeWrite(int n) {
                super.beforeWrite(n);
                int percent = Math.round((getCount() * 100) / lenghtOfFile);
                Log.d("FTP_DOWNLOAD", "bytesTransferred /downloaded"+percent);
                System.err.println("Downloaded "+getCount() + "/" + percent);
                mProgress.setProgress(percent);
            }
        };
        ftp.setBufferSize(2024*2048);//To increase the  download speed
        ftp.retrieveFile(serverFilePath, output);
        output.close();
        ftp.noop(); // check that control connection is working OK
        ftp.logout();
        return true;
    }
    catch (FTPConnectionClosedException e) {
        Log.d("FTP_DOWNLOAD", "ERROR FTPConnectionClosedException:"+e.toString());
        throw e;
    } catch (IOException e) {
        Log.d("FTP_DOWNLOAD", "ERROR IOException:"+e.toString());
        throw e;
    } catch (Exception e) {
        Log.d("FTP_DOWNLOAD", "ERROR Exception:"+e.toString());
        throw e;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                throw f;
            }
        }
    }
}
private static long getFileSize(FTPClient ftp, String filePath) throws Exception {
    long fileSize = 0;
    FTPFile[] files = ftp.listFiles(filePath);
    if (files.length == 1 && files[0].isFile()) {
        fileSize = files[0].getSize();
    }
    Log.d("FTP_DOWNLOAD", "File size = " + fileSize);
    return fileSize;
 }
 }

По сути, пользовательский интерфейс не обновляется, также я не уверен, является ли CountingOutputStream правильным методом для определения размера загруженного файла.

Заранее спасибо.

1 Ответ

0 голосов
/ 13 июня 2019

Я изменил этот раздел кода retrieveFile, и теперь все нормально

ftp.retrieveFile (serverFilePath, cos);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...