Android上传视频到Asynctask

时间:2014-06-03 10:45:04

标签: android android-asynctask scribe

我写的代码女巫可以在vimeo.i上传视频使用scribe library.code工作完美。现在我想用Asynctask上传视频。我不知道我现在怎么能用aAsynctask 这是一个上传视频源

upload_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            try {
                accessToken = checkToken(vimeoAPIURL, accessToken, service);
                if (accessToken == null) {
                    System.out.println("Error");
                }
                UploadVideoinVimeo();


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });





public void UploadVideoinVimeo() throws Exception {
    request = new OAuthRequest(Verb.GET, vimeoAPIURL);
    request.addQuerystringParameter("method",
            "vimeo.videos.upload.getQuota");
    signAndSendToVimeo(request, "getQuota", true);

    // Get Ticket
    request = new OAuthRequest(Verb.GET, vimeoAPIURL);
    request.addQuerystringParameter("method",
            "vimeo.videos.upload.getTicket");
    request.addQuerystringParameter("upload_method", "streaming");
    response = signAndSendToVimeo(request, "getTicket", true);

    // Get Endpoint and ticket ID
    System.out.println(newline + newline
            + "We're sending the video for upload!");
    Document doc = readXML(response.getBody());
    Element ticketElement = (Element) doc.getDocumentElement()
            .getElementsByTagName("ticket").item(0);
    String endpoint = ticketElement.getAttribute("endpoint");
    String ticketId = ticketElement.getAttribute("id");
    // Setup File
    File testUp = new File(mVideoFilename);
    boolean sendVideo = sendVideo(endpoint, testUp);
    if (!sendVideo) {
        throw new Exception("Didn't successfully send the video.");
    }

    // Complete Upload
    request = new OAuthRequest(Verb.PUT, vimeoAPIURL);
    request.addQuerystringParameter("method",
            "vimeo.videos.upload.complete");
    request.addQuerystringParameter("filename", testUp.getName());
    request.addQuerystringParameter("ticket_id", ticketId);
    Response completeResponse = signAndSendToVimeo(request, "complete",
            true);

    // Set video info
    setVimeoVideoInfo(completeResponse, service, accessToken, vimeoAPIURL);
}

private static boolean sendVideo(String endpoint, File file)
        throws FileNotFoundException, IOException {
    // Setup File
    long contentLength = file.length();
    String contentLengthString = Long.toString(contentLength);
    int size = (int) file.length();
    FileInputStream is = new FileInputStream(file);

    byte[] bytesPortion = new byte[size];
    int maxAttempts = 5; // This is the maximum attempts that will be given
                            // to resend data if the vimeo server doesn't
                            // have the right number of bytes for the given
                            // portion of the video
    long lastByteOnServer = 0;
    boolean first = false;
    while (is.read(bytesPortion, 0, size) != -1) {
        lastByteOnServer = prepareAndSendByteChunk(endpoint,
                contentLengthString, lastByteOnServer, bytesPortion, first,
                0, maxAttempts);
        if (lastByteOnServer == -1) {
            return false;
        }
        first = true;
        // getProgressBar().setValue(NumberHelper.getPercentFromTotal(byteNumber,
        // getFileSize()));
    }
    return true;
}

/**
 * Prepares the given bytes to be sent to Vimeo
 * 
 * @param endpoint
 * @param contentLengthString
 * @param lastByteOnServer
 * @param byteChunk
 * @param first
 * @param attempt
 * @param maxAttempts
 * @return number of bytes currently on the server
 * @throws FileNotFoundException
 * @throws IOException
 */
private static long prepareAndSendByteChunk(String endpoint,
        String contentLengthString, long lastByteOnServer,
        byte[] byteChunk, boolean first, int attempt, int maxAttempts)
        throws FileNotFoundException, IOException {
    if (attempt > maxAttempts) {
        return -1;
    } else if (attempt > 0) {
        System.out.println("Attempt number " + attempt + " for video "
                + "Test Video");
    }
    long totalBytesShouldBeOnServer = lastByteOnServer + byteChunk.length;
    String contentRange = lastByteOnServer + "-"
            + totalBytesShouldBeOnServer;
    long bytesOnServer = sendVideoBytes(endpoint, contentLengthString,
            "video/mp4", contentRange, byteChunk, first);
    if (bytesOnServer != totalBytesShouldBeOnServer) {
        System.err.println(bytesOnServer + " (bytesOnServer)" + " != "
                + totalBytesShouldBeOnServer
                + " (totalBytesShouldBeOnServer)");
        long remainingBytes = totalBytesShouldBeOnServer - bytesOnServer;
        int beginning = (int) (byteChunk.length - remainingBytes);
        int ending = (int) byteChunk.length;
        byte[] newByteChunk = Arrays.copyOfRange(byteChunk, beginning,
                ending);
        return prepareAndSendByteChunk(endpoint, contentLengthString,
                bytesOnServer, newByteChunk, first, attempt + 1,
                maxAttempts);
    } else {
        return bytesOnServer;
    }
}

/**
 * Sends the given bytes to the given endpoint
 * 
 * @return the last byte on the server (from verifyUpload(endpoint))
 */
private static long sendVideoBytes(String endpoint, String contentLength,
        String fileType, String contentRange, byte[] fileBytes,
        boolean addContentRange) throws FileNotFoundException, IOException {
    OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
    request.addHeader("Content-Range", "bytes" + contentRange);
    // request.addHeader("Content-Length", contentLength);
    request.addHeader("Content-Type", fileType);
    if (addContentRange) {
        request.addHeader("Content-Range", "bytes " + contentRange);
    }
    request.addPayload(fileBytes);
    Response response = signAndSendToVimeo(request, "sendVideo on "
            + "Test title", false);
    if (response.getCode() != 200 && !response.isSuccessful()) {
        return -1;
    }
    return verifyUpload(endpoint);
}

/**
 * Verifies the upload and returns whether it's successful
 * 
 * @param endpoint
 *            to verify upload to
 * @return the last byte on the server
 */
private static long verifyUpload(String endpoint) {
    // Verify the upload
    OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
    request.addHeader("Content-Length", "0");
    request.addHeader("Content-Range", "bytes */*");
    Response response = signAndSendToVimeo(request, "verifyUpload to "
            + endpoint, true);
    if (response.getCode() != 308 || !response.isSuccessful()) {
        return -1;
    }
    String range = response.getHeader("Range");
    // range = "bytes=0-10485759"
    return Long.parseLong(range.substring(range.lastIndexOf("-") + 1)) + 1;
    // The + 1 at the end is because Vimeo gives you 0-whatever byte where 0
    // = the first byte
}

/**
 * Checks the token to make sure it's still valid. If not, it pops up a
 * dialog asking the user to authenticate.
 */
private static Token checkToken(String vimeoAPIURL, Token vimeoToken,
        OAuthService vimeoService) {
    if (vimeoToken == null) {
        // vimeoToken = getNewToken(vimeoService);
    } else {
        OAuthRequest request = new OAuthRequest(Verb.GET, vimeoAPIURL);
        request.addQuerystringParameter("method",
                "vimeo.oauth.checkAccessToken");
        Response response = signAndSendToVimeo(request, "checkAccessToken",
                true);
        if (response.isSuccessful()
                && (response.getCode() != 200
                        || response.getBody().contains("<err code=\"302\"") || response
                        .getBody().contains("<err code=\"401\""))) {
            // vimeoToken = getNewToken(vimeoService);
        }
    }
    return vimeoToken;
}

/**
 * Gets authorization URL, pops up a dialog asking the user to authenticate
 * with the url and the user returns the authorization code
 * 
 * @param service
 * @return
 */
/**
 * Sets the video's meta-data
 */
private static void setVimeoVideoInfo(Response response,
        OAuthService service, Token token, String vimeoAPIURL) {
    OAuthRequest request;
    Document doc = readXML(response.getBody());
    org.w3c.dom.Element ticketElement = (org.w3c.dom.Element) doc
            .getDocumentElement().getElementsByTagName("ticket").item(0);
    String vimeoVideoId = ticketElement.getAttribute("video_id");
    GlobalClasses.VimeoId = vimeoVideoId;
    // Set title, description, category, tags, private
    // Set Title
    request = new OAuthRequest(Verb.POST, vimeoAPIURL);
    request.addQuerystringParameter("method", "vimeo.videos.setTitle");
    request.addQuerystringParameter("title", "1322");
    request.addQuerystringParameter("video_id", vimeoVideoId);

    signAndSendToVimeo(request, "setTitle", true);

    // Set description
    request = new OAuthRequest(Verb.POST, vimeoAPIURL);
    request.addQuerystringParameter("method", "vimeo.videos.setDescription");
    request.addQuerystringParameter("description",
            "This is my test description");
    request.addQuerystringParameter("video_id", GlobalClasses.VimeoId);
    signAndSendToVimeo(request, "setDescription", true);

    List<String> videoTags = new ArrayList<String>();
    videoTags.add("test1");
    videoTags.add("");
    videoTags.add("test3");
    videoTags.add("test4");
    videoTags.add("test 5");
    videoTags.add("test-6");
    videoTags
            .add("test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7");

    // Create tags string
    String tags = "";
    for (String tag : videoTags) {
        tags += tag + ", ";
    }
    tags.replace(", , ", ", "); // if by chance there are empty tags.

    // Set Tags
    request = new OAuthRequest(Verb.POST, vimeoAPIURL);
    request.addQuerystringParameter("method", "vimeo.videos.addTags");
    request.addQuerystringParameter("tags", tags);
    request.addQuerystringParameter("video_id", vimeoVideoId);
    signAndSendToVimeo(request, "addTags", true);

    // Set Privacy
    request = new OAuthRequest(Verb.POST, vimeoAPIURL);
    request.addQuerystringParameter("method", "vimeo.videos.setPrivacy");
    request.addQuerystringParameter("privacy", (true) ? "nobody"
            : "anybody");
    request.addQuerystringParameter("video_id", vimeoVideoId);
    signAndSendToVimeo(request, "setPrivacy", true);
}

/**
 * Signs the request and sends it. Returns the response.
 * 
 * @param request
 * @return response
 */
public static Response signAndSendToVimeo(OAuthRequest request,
        String description, boolean printBody)
        throws org.scribe.exceptions.OAuthException {
    System.out
            .println(newline
                    + newline
                    + "Signing "
                    + description
                    + " request:"
                    + ((printBody && !request.getBodyContents().isEmpty()) ? newline
                            + "\tBody Contents:"
                            + request.getBodyContents()
                            : "")
                    + ((!request.getHeaders().isEmpty()) ? newline
                            + "\tHeaders: " + request.getHeaders() : ""));
    service.signRequest(accessToken, request);
    printRequest(request, description);
    Response response = request.send();
    printResponse(response, description, printBody);
    return response;
}

/**
 * Prints the given description, and the headers, verb, and complete URL of
 * the request.
 * 
 * @param request
 * @param description
 */
private static void printRequest(OAuthRequest request, String description) {
    System.out.println();
    System.out.println(description + " >>> Request");
    System.out.println("Headers: " + request.getHeaders());
    System.out.println("Verb: " + request.getVerb());
    System.out.println("Complete URL: " + request.getCompleteUrl());
}

/**
 * Prints the given description, and the code, headers, and body of the
 * given response
 * 
 * @param response
 * @param description
 */
private static void printResponse(Response response, String description,
        boolean printBody) {
    System.out.println();
    System.out.println(description + " >>> Response");
    System.out.println("Code: " + response.getCode());
    System.out.println("Headers: " + response.getHeaders());
    if (printBody) {
        System.out.println("Body: " + response.getBody());
    }
}

/**
 * This method will Read the XML and act accordingly
 * 
 * @param xmlString
 *            - the XML String
 * @return the list of elements within the XML
 */
private static Document readXML(String xmlString) {
    Document doc = null;
    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource xmlStream = new InputSource();
        xmlStream.setCharacterStream(new StringReader(xmlString));
        doc = dBuilder.parse(xmlStream);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return doc;
}

如何重写此代码以使用Asynctask?如果有人知道解决方案帮助我

1 个答案:

答案 0 :(得分:0)

创建一个扩展AsyncTask的类,并将async方法放在doInBackground(...)中,如下所示:

    private class VideoUpload extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        //your upload code here
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {}

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

然后像这样调用你的asyncTask:

new VideoUpload().execute();