AsyncTask上传视频冻结用户界面

时间:2014-12-17 06:27:35

标签: android performance android-asynctask

在将视频上传到服务器时,UI冻结直到视频上传完成,我做了大量的谷歌搜索和读取堆栈溢出帖子但没有得到任何解决方案。任何帮助将受到高度赞赏。视频上传成功但问题是app UI冻结。

这里调用Asynctask,将视频上传到服务器。

AsyncVideoUploader client_ = new AsyncVideoUploader(false,ApiTask.CREATE_POST_VIDEO,this);
client_.execute("file1", videoPath, serviceArgs_);

这是上传视频的实际Asynctask。

public class AsyncVideoUploader extends AsyncTask<Object, Integer, String> {
private AsyncTaskListener delegate;
private ApiTask task;
Object[] payload;
int responseCode = -1;
String responseMessage = "";
boolean isStartTimer = false,isSentMaxSize = false;
int maxSizeToSent;
int progressValue;
Timer timer = new Timer();

public AsyncVideoUploader(boolean secure, ApiTask task, AsyncTaskListener delegate) {
    this.task = task;
    this.delegate = delegate;
    payload = null;
}

public AsyncVideoUploader(boolean secure, ApiTask task, AsyncTaskListener delegate, Object... payload) {
    this.task = task;
    this.delegate = delegate;
    this.payload = payload;
}

@Override
@SuppressWarnings("unchecked")
protected String doInBackground(Object... args) {

    HttpURLConnection httpURLConnection_ = null;
    DataOutputStream dataOutputStream_ = null;
    // DataInputStream dataInputStream_ = null;

    int bytesRead_, bytesAvailable_, bufferSize_;
    byte[] buffer_;
    int maxBufferSize_ = 1*1024; // 8 Megabytes max

    String endLine_ = "\r\n";
    String twoHyphens_ = "--";
    String boundary_ = "*****";

    String videoName_ = (String) args[0];
    String videoPath_ = (String) args[1];
    String fileName_ = Utils.getFileNameFromPath(videoPath_);
    long lengthOfFile;
    int total = 0;

    Map<String, String> serviceArgs_ = (Map<String, String>) args[2];

    FileInputStream inputStream_ = null;
    try {
        inputStream_ = new FileInputStream(new File(videoPath_));
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {

        URL url_ = new URL(Consts.URL.VIDEO_UPLOAD_HTTP); 
        httpURLConnection_ = (HttpURLConnection)url_.openConnection();
        httpURLConnection_.setRequestMethod("POST");
        httpURLConnection_.setDoInput (true);
        httpURLConnection_.setDoOutput (true);
        httpURLConnection_.setUseCaches (false);
        httpURLConnection_.setChunkedStreamingMode(1024);
        httpURLConnection_.setConnectTimeout(Consts.HTTP_REQUEST_TIMEOUT);
        httpURLConnection_.setReadTimeout(Consts.HTTP_REQUEST_TIMEOUT);
        httpURLConnection_.setRequestProperty("Connection", "keep-alive");
        httpURLConnection_.setRequestProperty("ENCTYPE", "multipart/form-data");
        httpURLConnection_.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary_); 
        httpURLConnection_.connect();

        dataOutputStream_ = new DataOutputStream(httpURLConnection_.getOutputStream()); 

        // Video
        dataOutputStream_.writeBytes(twoHyphens_ + boundary_ + endLine_);
        dataOutputStream_.writeBytes("Content-Disposition:form-data;name=\"" + videoName_ + "\";filename=\"" + fileName_ + "\"" + endLine_); 
        dataOutputStream_.writeBytes("Content-type:application/octet-stream" + endLine_);
        dataOutputStream_.writeBytes(endLine_);
        bytesAvailable_ = inputStream_.available();
        lengthOfFile = new File(videoPath_).length();
        maxSizeToSent = bytesAvailable_;
        bufferSize_ = Math.min(bytesAvailable_, maxBufferSize_);
        buffer_ = new byte[bufferSize_];
        bytesRead_ = inputStream_.read(buffer_, 0, bufferSize_);
        while (bytesRead_ > 0)
        {

            total += bytesRead_;
            try {
                dataOutputStream_.write(buffer_, 0, bufferSize_);
                publishProgress((int)((total * 100) / lengthOfFile));
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }

             bytesAvailable_ = inputStream_.available();
             Log.e("Bytes Available:", ""+bytesAvailable_);
             bufferSize_ = Math.min(bytesAvailable_, maxBufferSize_);
             bytesRead_ = inputStream_.read(buffer_, 0, bufferSize_);
        }
        dataOutputStream_.writeBytes(endLine_);


        // Other arguments
        Iterator<String> serviceArgsIterator_ = serviceArgs_.keySet().iterator();
        while(serviceArgsIterator_.hasNext()) {
            String key_   = (String) serviceArgsIterator_.next();
            String value_ = (String) serviceArgs_.get(key_);

            dataOutputStream_.writeBytes(twoHyphens_ + boundary_ + endLine_);
            dataOutputStream_.writeBytes("Content-Disposition:form-data;name=\"" + key_ + "\"" + endLine_);
            dataOutputStream_.writeBytes(endLine_);
            dataOutputStream_.writeBytes(value_);
            dataOutputStream_.writeBytes(endLine_); 
        }

        dataOutputStream_.writeBytes(twoHyphens_ + boundary_ + twoHyphens_ + endLine_);
        dataOutputStream_.flush();
        dataOutputStream_.close();
        inputStream_.close();

        if (httpURLConnection_.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return Utils.convertInputStreamToString(httpURLConnection_.getInputStream());
        }
        else {  
            this.responseCode = httpURLConnection_.getResponseCode();
            this.responseMessage = httpURLConnection_.getResponseMessage();

            return null;
        }
    }
    catch (MalformedURLException e) {  
        e.printStackTrace();  
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if(httpURLConnection_ != null) {
            httpURLConnection_.disconnect();  
        }
    }
    return null;
}

@Override
protected void onPostExecute(String response) {
    String response_ = Utils.getValid(response);
    if(Utils.isValid(response_)) {
        if(Utils.isValid(this.payload)) {
            this.delegate.onTaskComplete(this.task, response_, this.payload);
            return;
        }
        else {
            this.delegate.onTaskComplete(this.task, response_);
            return;
        }
    }
    else {
        this.delegate.onTaskError(this.task, "Service is temporarily unavailable > " + this.responseMessage , this.responseCode);
        return;
    }
}

@Override
protected void onProgressUpdate(final Integer... values) {
    super.onProgressUpdate(values);
    Log.e("Bytes uploaded", String.valueOf(values[0]));
    progressValue = values[0];
    delegate.onProgressUpdate(task , progressValue, 0);
}

}

0 个答案:

没有答案