Example usage for android.os Handler postDelayed

List of usage examples for android.os Handler postDelayed

Introduction

In this page you can find the example usage for android.os Handler postDelayed.

Prototype

public final boolean postDelayed(Runnable r, long delayMillis) 

Source Link

Document

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.

Usage

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToFacebook(final Activity activity, final Handler handler, final Facebook mFacebook,
        final String path, final String title, final String description, final String emailAddress,
        final long sdrecord_id) {

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // Track errors
            boolean failed = false;

            Log.i(TAG, "Upload starting");
            // Initialising REST API video.upload parameters
            Bundle params = new Bundle();

            params.putString("method", "facebook.video.upload");
            params.putString("format", "json");
            params.putString("title", title);
            params.putString("description", description);
            params.putString("call_id", String.valueOf(System.currentTimeMillis()));
            params.putString("v", "1.0");
            params.putString("oauth_token", mFacebook.getAccessToken());

            // Reading input file
            try {
                File videoFile = new File(path);
                byte[] data = null;
                try {

                    // XXX
                    // SPLIT THIS INTO 5K chunks!!
                    // XXX

                    data = new byte[(int) videoFile.length()];
                } catch (OutOfMemoryError e) {
                    failed = true;/*from  w w  w.  j  av  a2 s.c  o  m*/
                }
                if (data != null) {
                    InputStream is = new FileInputStream(videoFile);
                    is.read(data);
                    params.putByteArray(videoFile.getName(), data);
                }
            } catch (Exception ex) {
                Log.e(TAG, "Cannot read video file :", ex);
            }

            // Sending POST request to Facebook
            String response = null;
            String url = "https://api-video.facebook.com/restserver.php";

            try {
                if (!failed) {
                    response = Util.openUrl(url, "POST", params);
                }
                // SessionEvents.onUploadComplete(response);
            } catch (FileNotFoundException e) {
                // SessionEvents.onFileNotFoundException(e);
                failed = true;
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // SessionEvents.onMalformedURLException(e);
                failed = true;
                e.printStackTrace();
            } catch (IOException e) {
                // SessionEvents.onIOException(e);
                failed = true;
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                failed = true;
                e.printStackTrace();
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

                return;
            }

            Log.i(TAG, "Uploading to facebook complete. Response is " + response);

            // response is JSON
            JSONObject fb_response = null;
            // decode, and grab URL
            try {
                fb_response = (JSONObject) new JSONTokener(response).nextValue();
            } catch (JSONException e) {
                //
                e.printStackTrace();
                fb_response = null;
            }
            String hosted_url = "facebook.com";

            if (fb_response != null) {

                try {
                    hosted_url = fb_response.getString("link");
                    Log.i(TAG, "Facebook hosted url is : " + hosted_url);
                } catch (JSONException e) {
                    //
                    e.printStackTrace();
                    hosted_url = null;
                }

                if (hosted_url != null) {
                    // Log record of this URL in POSTs table
                    dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, url, hosted_url, "");

                    mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                    // Use the handler to execute a Runnable on the
                    // main thread in order to have access to the
                    // UI elements.
                    handler.postDelayed(new Runnable() {

                        public void run() {
                            // Update UI

                            // Indicate back to calling activity the result!
                            // update uploadInProgress state also.

                            ((VidiomActivity) activity).finishedUploading(true);
                            ((VidiomActivity) activity)
                                    .createNotification(res.getString(R.string.upload_to_facebook_succeeded_));

                        }
                    }, 0);
                }

            } else {

                // an error -- fb_response is NULL.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

            }

            if (emailAddress != null && fb_response != null && hosted_url != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + hosted_url, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

        }
    });

    t.start();

    return t;

}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private void processPickResult(final Intent data) {
    // The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
    // multiple phone picker.
    final Parcelable[] uris = data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);

    final int recipientCount = uris != null ? uris.length : 0;

    final int recipientLimit = MmsConfig.getRecipientLimit();
    if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
                .setPositiveButton(android.R.string.ok, null).create().show();
        return;/*from   w  ww  . ja  va  2s . com*/
    }

    final Handler handler = new Handler();
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
    progressDialog.setMessage(getText(R.string.adding_recipients));
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);

    final Runnable showProgress = new Runnable() {
        @Override
        public void run() {
            progressDialog.show();
        }
    };
    // Only show the progress dialog if we can not finish off parsing the return data in 1s,
    // otherwise the dialog could flicker.
    handler.postDelayed(showProgress, 1000);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final ContactList list;
            try {
                list = ContactList.blockingGetByUris(uris);
            } finally {
                handler.removeCallbacks(showProgress);
                progressDialog.dismiss();
            }
            // TODO: there is already code to update the contact header widget and recipients
            // editor if the contacts change. we can re-use that code.
            final Runnable populateWorker = new Runnable() {
                @Override
                public void run() {
                    mRecipientsEditor.populate(list);
                    updateTitle(list);
                }
            };
            handler.post(populateWorker);
        }
    }, "ComoseMessageActivity.processPickResult").start();
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title,
        String description, boolean retry, long sdrecord_id) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);/*from   w  ww.  j  ava2 s.  co m*/
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    // urlConnection.setRequestProperty("Content-Length", newValue);
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData = null;

    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    String template = readFile(activity, R.raw.gdata).toString();

    // Workarounds for corner cases. Youtube doesnt like empty titles
    if (title == null || title.length() == 0) {
        title = "Untitled";
    }
    if (description == null || description.length() == 0) {
        description = "No description";
    }

    // Check user preference to see if YouTube videos should be private by
    // default.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
    Boolean ytPrivate = prefs.getBoolean("defaultYouTubePrivatePreference", true);

    String private_or_not = "<yt:private />";
    if (!ytPrivate) {
        private_or_not = "";
    }

    atomData = String.format(template, title, description, category, this.tags, private_or_not);

    OutputStreamWriter outStreamWriter = null;
    int responseCode = -1;

    try {
        outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
        outStreamWriter.write(atomData);
        outStreamWriter.close();

        /*
         * urlConnection.connect(); InputStream is =
         * urlConnection.getInputStream(); BufferedReader in = new
         * BufferedReader(new InputStreamReader(is)); String inputLine;
         * 
         * while ((inputLine = in.readLine()) != null) {
         * Log.d(TAG,inputLine); } in.close();
         */

        responseCode = urlConnection.getResponseCode();

        // ERROR LOGGING
        InputStream is = urlConnection.getErrorStream();
        if (is != null) {
            Log.e(TAG, " Error stream from Youtube available!");
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, inputLine);
            }
            in.close();

            Map<String, List<String>> hfs = urlConnection.getHeaderFields();
            for (Entry<String, List<String>> hf : hfs.entrySet()) {
                Log.d(TAG, " entry : " + hf.getKey());
                List<String> vals = hf.getValue();
                for (String s : vals) {
                    Log.d(TAG, "vals:" + s);
                }
            }
        }

    } catch (IOException e) {
        //
        // Catch IO Exceptions here, like UnknownHostException, so we can
        // detect network failures, and send a notification
        //
        Log.d(TAG, " Error occured in uploadMetaData! ");
        e.printStackTrace();
        responseCode = -1;
        outStreamWriter = null;

        mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((VidiomActivity) activity).finishedUploading(false);
                ((VidiomActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

            }
        }, 0);

        // forward it on!
        throw e;
    }

    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(activity, handler, filePath, title, description, false, sdrecord_id);
        } else {

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

            // Probably not authorised!

            // Need to setup a Youtube account.

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(false);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

                }
            }, 0);

            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));

        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void showFileListCache(final ArrayList<FileListCacheItem> fcl, final FileListAdapter fla,
        final ListView flv, final Spinner spinner) {
    // ??//w  ww  .  ja  va 2s  .  c o  m
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setContentView(R.layout.select_file_cache_dlg);
    //      final Button btnOk = 
    //            (Button) dialog.findViewById(R.id.select_file_cache_dlg_ok);
    final Button btnCancel = (Button) dialog.findViewById(R.id.select_file_cache_dlg_cancel);

    CommonDialog.setDlgBoxSizeCompact(dialog);

    ((TextView) dialog.findViewById(R.id.select_file_cache_dlg_title)).setText("Select file cache");

    ListView lv = (ListView) dialog.findViewById(R.id.select_file_cache_dlg_listview);

    final ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < fcl.size(); i++) {
        list.add(fcl.get(i).directory);
    }
    Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String lhs, String rhs) {
            return lhs.compareToIgnoreCase(rhs);
        }
    });
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.simple_list_item_1o, list);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String t_dir = list.get(position);
            FileListCacheItem dhi = getFileListCache(t_dir, fcl);
            if (dhi != null) {
                mIgnoreSpinnerSelection = true;
                int s_no = -1;
                for (int i = 0; i < spinner.getCount(); i++) {
                    if (spinner.getItemAtPosition(i).toString().equals(dhi.profile_name)) {
                        s_no = i;
                        break;
                    }
                }
                fla.setDataList(dhi.file_list);
                fla.notifyDataSetChanged();
                if (currentTabName.equals(SMBEXPLORER_TAB_LOCAL)) {
                    localBase = dhi.base;
                    if (dhi.base.equals(dhi.directory))
                        localDir = "";
                    else
                        localDir = dhi.directory.replace(localBase + "/", "");
                    replaceDirHist(localDirHist, dhi.directory_history);
                    setFilelistCurrDir(localFileListDirSpinner, localBase, localDir);
                    setFileListPathName(localFileListPathBtn, localFileListCache, localBase, localDir);
                    setEmptyFolderView();
                    localCurrFLI = dhi;
                    flv.setSelection(0);
                    for (int j = 0; j < localFileListView.getChildCount(); j++)
                        localFileListView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
                    localFileListReloadBtn.performClick();
                } else if (currentTabName.equals(SMBEXPLORER_TAB_REMOTE)) {
                    remoteBase = dhi.base;
                    if (dhi.base.equals(dhi.directory))
                        remoteDir = "";
                    else
                        remoteDir = dhi.directory.replace(remoteBase + "/", "");
                    replaceDirHist(remoteDirHist, dhi.directory_history);
                    setFilelistCurrDir(remoteFileListDirSpinner, remoteBase, remoteDir);
                    setFileListPathName(remoteFileListPathBtn, remoteFileListCache, remoteBase, remoteDir);
                    setEmptyFolderView();
                    remoteCurrFLI = dhi;
                    flv.setSelection(0);

                    //                  Log.v("","base="+remoteBase+", dir="+remoteDir+", histsz="+remoteDirHist.size());
                    for (int j = 0; j < remoteFileListView.getChildCount(); j++)
                        remoteFileListView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
                    if (remoteDir.equals("")) {
                        remoteFileListTopBtn.setEnabled(false);
                        remoteFileListUpBtn.setEnabled(false);
                    } else {
                        remoteFileListTopBtn.setEnabled(true);
                        remoteFileListUpBtn.setEnabled(true);
                    }
                }

                if (s_no != -1)
                    spinner.setSelection(s_no);
                Handler hndl = new Handler();
                hndl.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIgnoreSpinnerSelection = false;
                    }
                }, 100);
                dialog.dismiss();
            }
        }
    });

    btnCancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();

}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;/*ww  w .ja v  a2  s .c  o m*/
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            // CHECK RESPONSE FOR SUCCESS!!
            if (!failed && response != null
                    && response.matches(res.getString(R.string.video_bin_API_good_re))) {
                // We got back HTTP response with valid URL
                Log.d(TAG, " video bin got back URL " + response);

            } else {
                Log.d(TAG, " video bin got eror back:\n" + response);
                failed = true;
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);

                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(true);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();

            if (useProxy) {
                HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }/*from ww w . j  a v a2  s  .  c om*/

            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {
                        int lastPercent = 0;

                        @Override
                        public void transferred(long num) {

                            percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f);
                            //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength);
                            if (lastPercent != percentUploaded) {
                                ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded);
                                lastPercent = percentUploaded;
                            }
                        }

                    });

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            totalLength = entity.getContentLength();

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((SSCXferActivity) activity).finishedUploading(false);

                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            Log.d(TAG, " video bin got back " + response);

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

private String startYouTubeUpload(final Activity activity, File file, final Handler handler,
        final String emailAddress, final long sdrecord_id) throws IOException, YouTubeAccountException,
        SAXException, ParserConfigurationException, Internal500ResumeException {

    if (this.clientLoginToken == null) {
        // The stored gmail account is not linked to YouTube
        throw new YouTubeAccountException(this.youTubeName + " is not linked to a YouTube account.");
    }/*from   w  ww  .  ja  v  a 2 s. co m*/

    String[] strs = dbutils.getTitleAndDescriptionFromID(new String[] { Long.toString(sdrecord_id) });

    String uploadUrl = uploadMetaData(activity, handler, file.getAbsolutePath(), strs[0], strs[1], true);

    //Log.d(TAG, "uploadUrl=" + uploadUrl + " youtube account name is "
    //   + this.youTubeName);
    //Log.d(TAG, String.format("Client token : %s ", this.clientLoginToken));

    this.currentFileSize = file.length();
    this.totalBytesUploaded = 0;
    this.numberOfRetries = 0;

    int uploadChunk = 1024 * 1024 * 3; // 3MB

    int start = 0;
    int end = -1;

    String videoId = null;
    double fileSize = this.currentFileSize;
    while (fileSize > 0) {
        if (fileSize - uploadChunk > 0) {
            end = start + uploadChunk - 1;
        } else {
            end = start + (int) fileSize - 1;
        }
        Log.d(TAG, String.format("start=%s end=%s total=%s", start, end, file.length()));
        try {
            videoId = gdataUpload(file, uploadUrl, start, end, activity);
            fileSize -= uploadChunk;
            start = end + 1;
            this.numberOfRetries = 0; // clear this counter as we had a
            // successful upload
        } catch (IOException e) {
            Log.d(TAG, "Error during upload : " + e.getMessage());
            ResumeInfo resumeInfo = null;
            do {
                if (!shouldResume()) {
                    Log.d(TAG, String.format("Giving up uploading '%s'.", uploadUrl));
                    throw e;
                }
                try {
                    resumeInfo = resumeFileUpload(uploadUrl);
                } catch (IOException re) {
                    // ignore
                    Log.d(TAG, String.format("Failed retry attempt of : %s due to: '%s'.", uploadUrl,
                            re.getMessage()));
                }
            } while (resumeInfo == null);
            Log.d(TAG, String.format("Resuming stalled upload to: %s.", uploadUrl));
            if (resumeInfo.videoId != null) { // upload actually complted
                // despite the exception
                videoId = resumeInfo.videoId;
                Log.d(TAG, String.format("No need to resume video ID '%s'.", videoId));
                break;
            } else {
                int nextByteToUpload = resumeInfo.nextByteToUpload;
                Log.d(TAG, String.format("Next byte to upload is '%d'.", nextByteToUpload));
                this.totalBytesUploaded = nextByteToUpload; // possibly
                // rolling back
                // the
                // previously
                // saved value
                fileSize = this.currentFileSize - nextByteToUpload;
                start = nextByteToUpload;
            }
        }
    }

    if (videoId != null) {

        if (emailAddress != null) {

            // EmailSender through IR controlled mail system.
            SSLEmailSender sender = new SSLEmailSender(activity.getString(R.string.automatic_email_username),
                    activity.getString(R.string.automatic_email_password)); // consider
            // this
            // public
            // knowledge.
            try {
                sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                        activity.getString(R.string.url_of_hosted_video_is_) + " " + YOUTUBE_PLAYER_URL
                                + videoId, // body.getText().toString(),
                        activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                        emailAddress // to.getText().toString()
                );
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }

        // Log record of this URL in POSTs table
        dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, uploadUrl, YOUTUBE_PLAYER_URL + videoId,
                "");

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((SSCXferActivity) activity).finishedUploading(true);
                ((SSCXferActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_succeeded_));

            }
        }, 0);

        return videoId;
    }

    return null;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String startYouTubeUpload(final Activity activity, File file, final Handler handler,
        final String emailAddress, final long sdrecord_id) throws IOException, YouTubeAccountException,
        SAXException, ParserConfigurationException, Internal500ResumeException {

    if (this.clientLoginToken == null) {
        // The stored gmail account is not linked to YouTube
        throw new YouTubeAccountException(this.youTubeName + " is not linked to a YouTube account.");
    }/* w  w  w  . j ava  2  s  .co m*/

    String[] strs = dbutils.getTitleAndDescriptionFromID(new String[] { Long.toString(sdrecord_id) });
    // add our branding to the description.
    String uploadUrl = uploadMetaData(activity, handler, file.getAbsolutePath(), strs[0], strs[1], true,
            sdrecord_id);

    Log.d(TAG, "uploadUrl=" + uploadUrl + " youtube account name is " + this.youTubeName);
    Log.d(TAG, String.format("Client token : %s ", this.clientLoginToken));

    this.currentFileSize = file.length();
    this.totalBytesUploaded = 0;
    this.numberOfRetries = 0;

    int uploadChunk = 1024 * 1024 * 3; // 3MB

    int start = 0;
    int end = -1;

    String videoId = null;
    double fileSize = this.currentFileSize;
    while (fileSize > 0) {
        if (fileSize - uploadChunk > 0) {
            end = start + uploadChunk - 1;
        } else {
            end = start + (int) fileSize - 1;
        }
        Log.d(TAG, String.format("start=%s end=%s total=%s", start, end, file.length()));
        try {
            videoId = gdataUpload(file, uploadUrl, start, end);
            fileSize -= uploadChunk;
            start = end + 1;
            this.numberOfRetries = 0; // clear this counter as we had a
            // successful upload
        } catch (IOException e) {
            Log.d(TAG, "Error during upload : " + e.getMessage());
            ResumeInfo resumeInfo = null;
            do {
                if (!shouldResume()) {
                    Log.d(TAG, String.format("Giving up uploading '%s'.", uploadUrl));
                    throw e;
                }
                try {
                    resumeInfo = resumeFileUpload(uploadUrl);
                } catch (IOException re) {
                    // ignore
                    Log.d(TAG, String.format("Failed retry attempt of : %s due to: '%s'.", uploadUrl,
                            re.getMessage()));
                }
            } while (resumeInfo == null);
            Log.d(TAG, String.format("Resuming stalled upload to: %s.", uploadUrl));
            if (resumeInfo.videoId != null) { // upload actually complted
                // despite the exception
                videoId = resumeInfo.videoId;
                Log.d(TAG, String.format("No need to resume video ID '%s'.", videoId));
                break;
            } else {
                int nextByteToUpload = resumeInfo.nextByteToUpload;
                Log.d(TAG, String.format("Next byte to upload is '%d'.", nextByteToUpload));
                this.totalBytesUploaded = nextByteToUpload; // possibly
                // rolling back
                // the
                // previously
                // saved value
                fileSize = this.currentFileSize - nextByteToUpload;
                start = nextByteToUpload;
            }
        }
    }

    if (videoId != null) {

        if (emailAddress != null) {

            // EmailSender through IR controlled mail system.
            SSLEmailSender sender = new SSLEmailSender(activity.getString(R.string.automatic_email_username),
                    activity.getString(R.string.automatic_email_password)); // consider
            // this
            // public
            // knowledge.
            try {
                sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                        activity.getString(R.string.url_of_hosted_video_is_) + " " + YOUTUBE_PLAYER_URL
                                + videoId, // body.getText().toString(),
                        activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                        emailAddress // to.getText().toString()
                );
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }

        // Log record of this URL in POSTs table
        dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, uploadUrl, YOUTUBE_PLAYER_URL + videoId,
                "");

        mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((VidiomActivity) activity).finishedUploading(true);
                ((VidiomActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_succeeded_));

            }
        }, 0);

        return videoId;
    }

    return null;
}

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

private void scanRemoteNetwork(final Dialog dialog, final ListView lv_ipaddr,
        final AdapterScanAddressResultList adap, final ArrayList<ScanAddressResultListItem> ipAddressList,
        final String subnet, final int begin_addr, final int end_addr, final NotifyEvent p_ntfy) {
    final Handler handler = new Handler();
    final ThreadCtrl tc = new ThreadCtrl();
    final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_scan_address);
    final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_progress);
    final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_remote_ntwk_progress_msg);
    final Button btn_scan = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_ok);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_cancel);
    final Button scan_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_progress_cancel);

    final CheckedTextView ctv_use_port_number = (CheckedTextView) dialog
            .findViewById(R.id.scan_remote_ntwk_ctv_use_port);
    final EditText et_port_number = (EditText) dialog.findViewById(R.id.scan_remote_ntwk_port_number);

    tvmsg.setText("");
    scan_cancel.setText(R.string.msgs_scan_progress_spin_dlg_addr_cancel);
    ll_addr.setVisibility(LinearLayout.GONE);
    ll_prog.setVisibility(LinearLayout.VISIBLE);
    btn_scan.setVisibility(Button.GONE);
    btn_cancel.setVisibility(Button.GONE);
    adap.setButtonEnabled(false);/*from  w  w  w . j  a  v  a 2 s. c om*/
    scan_cancel.setEnabled(true);
    dialog.setOnKeyListener(new DialogBackKeyListener(mContext));
    dialog.setCancelable(false);
    // CANCEL?
    scan_cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            scan_cancel.setText(mContext.getString(R.string.msgs_progress_dlg_canceling));
            scan_cancel.setEnabled(false);
            util.addDebugMsg(1, "W", "IP Address list creation was cancelled");
            tc.setDisabled();
        }
    });
    dialog.show();

    util.addDebugMsg(1, "I", "Scan IP address ransge is " + subnet + "." + begin_addr + " - " + end_addr);

    final String scan_prog = mContext.getString(R.string.msgs_ip_address_scan_progress);
    String p_txt = String.format(scan_prog, 0);
    tvmsg.setText(p_txt);

    new Thread(new Runnable() {
        @Override
        public void run() {//non UI thread
            mScanCompleteCount = 0;
            mScanAddrCount = end_addr - begin_addr + 1;
            int scan_thread = 60;
            String scan_port = "";
            if (ctv_use_port_number.isChecked())
                scan_port = et_port_number.getText().toString();
            for (int i = begin_addr; i <= end_addr; i += scan_thread) {
                if (!tc.isEnabled())
                    break;
                boolean scan_end = false;
                for (int j = i; j < (i + scan_thread); j++) {
                    if (j <= end_addr) {
                        startRemoteNetworkScanThread(handler, tc, dialog, p_ntfy, lv_ipaddr, adap, tvmsg,
                                subnet + "." + j, ipAddressList, scan_port);
                    } else {
                        scan_end = true;
                    }
                }
                if (!scan_end) {
                    for (int wc = 0; wc < 210; wc++) {
                        if (!tc.isEnabled())
                            break;
                        SystemClock.sleep(30);
                    }
                }
            }
            if (!tc.isEnabled()) {
                handler.post(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                });
            } else {
                handler.postDelayed(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                }, 10000);
            }
        }
    }).start();
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void scanRemoteNetwork(final Dialog dialog, final ListView lv_ipaddr,
        final AdapterScanAddressResultList adap, final ArrayList<ScanAddressResultListItem> ipAddressList,
        final String subnet, final int begin_addr, final int end_addr, final NotifyEvent p_ntfy) {
    final Handler handler = new Handler();
    final ThreadCtrl tc = new ThreadCtrl();
    final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_scan_address);
    final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_progress);
    final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_remote_ntwk_progress_msg);
    final Button btn_scan = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_ok);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_cancel);
    final Button scan_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_progress_cancel);

    final CheckBox cb_use_port_number = (CheckBox) dialog.findViewById(R.id.scan_remote_ntwk_use_port);
    final EditText et_port_number = (EditText) dialog.findViewById(R.id.scan_remote_ntwk_port_number);

    tvmsg.setText("");
    scan_cancel.setText(R.string.msgs_progress_spin_dlg_addr_cancel);
    ll_addr.setVisibility(LinearLayout.GONE);
    ll_prog.setVisibility(LinearLayout.VISIBLE);
    btn_scan.setEnabled(false);//from   ww w .j ava2s  .co  m
    btn_cancel.setEnabled(false);
    adap.setButtonEnabled(false);
    scan_cancel.setEnabled(true);
    dialog.setOnKeyListener(new DialogBackKeyListener(mContext));
    dialog.setCancelable(false);
    // CANCEL?
    scan_cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            scan_cancel.setText(mContext.getString(R.string.msgs_progress_dlg_canceling));
            scan_cancel.setEnabled(false);
            sendDebugLogMsg(1, "W", "IP Address list creation was cancelled");
            tc.setDisabled();
        }
    });
    dialog.show();

    sendDebugLogMsg(1, "I", "Scan IP address ransge is " + subnet + "." + begin_addr + " - " + end_addr);

    final String scan_prog = mContext.getString(R.string.msgs_ip_address_scan_progress);
    String p_txt = String.format(scan_prog, 0);
    tvmsg.setText(p_txt);

    new Thread(new Runnable() {
        @Override
        public void run() {//non UI thread
            mScanCompleteCount = 0;
            mScanAddrCount = end_addr - begin_addr + 1;
            int scan_thread = 50;
            String scan_port = "";
            if (cb_use_port_number.isChecked())
                scan_port = et_port_number.getText().toString();
            for (int i = begin_addr; i <= end_addr; i += scan_thread) {
                if (!tc.isEnabled())
                    break;
                boolean scan_end = false;
                for (int j = i; j < (i + scan_thread); j++) {
                    if (j <= end_addr) {
                        startRemoteNetworkScanThread(handler, tc, dialog, p_ntfy, lv_ipaddr, adap, tvmsg,
                                subnet + "." + j, ipAddressList, scan_port);
                    } else {
                        scan_end = true;
                    }
                }
                if (!scan_end) {
                    for (int wc = 0; wc < 210; wc++) {
                        if (!tc.isEnabled())
                            break;
                        SystemClock.sleep(30);
                    }
                }
            }
            if (!tc.isEnabled()) {
                handler.post(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                });
            } else {
                handler.postDelayed(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                }, 10000);
            }
        }
    }).start();
}