List of usage examples for android.app Activity getString
@NonNull public final String getString(@StringRes int resId)
From source file:org.chromium.chrome.browser.tab.Tab.java
/** * Constructs and shows a sad tab (Aw, Snap!). *//*from www . j a va2 s.co m*/ protected void showSadTab() { if (getContentViewCore() != null) { OnClickListener suggestionAction = new OnClickListener() { @Override public void onClick(View view) { Activity activity = mWindowAndroid.getActivity().get(); assert activity != null; HelpAndFeedback.getInstance(activity).show(activity, activity.getString(R.string.help_context_sad_tab), Profile.getLastUsedProfile(), null); } }; // If the tab has crashed twice in a row change the button to "Send Feedback" and // change the onClickListener. final boolean showSendFeedbackButton = mSadTabSuccessiveRefreshCounter >= 1; OnClickListener buttonAction = new OnClickListener() { @Override public void onClick(View v) { if (showSendFeedbackButton) { getActivity().startHelpAndFeedback(Tab.this, "MobileSadTabFeedback"); } else { reload(); } } }; // Make sure we are not adding the "Aw, snap" view over an existing one. assert mSadTabView == null; mSadTabView = SadTabViewFactory.createSadTabView(mThemedApplicationContext, suggestionAction, buttonAction, showSendFeedbackButton ? R.string.sad_tab_send_feedback_label : R.string.sad_tab_reload_label); mSadTabSuccessiveRefreshCounter++; // Show the sad tab inside ContentView. getContentViewCore().getContainerView().addView(mSadTabView, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); notifyContentChanged(); } FullscreenManager fullscreenManager = getFullscreenManager(); if (fullscreenManager != null) { fullscreenManager.setPositionsForTabToNonFullscreen(); } }
From source file:com.android.gallery3d.app.PhotoPage.java
public void playVideo(Activity activity, Uri uri, String title) { try {//from w w w . j ava 2 s.c o m Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(uri, "video/*") .putExtra(Intent.EXTRA_TITLE, title).putExtra(MovieActivity.KEY_TREAT_UP_AS_BACK, true) /// M: [BUG.ADD] @{ .putExtra(MovieActivity.KEY_COME_FROM_CAMERA, mAppBridge != null); intent.putExtra(FeatureHelper.EXTRA_ENABLE_VIDEO_LIST, true); /// @} activity.startActivityForResult(intent, REQUEST_PLAY_VIDEO); } catch (ActivityNotFoundException e) { Toast.makeText(activity, activity.getString(R.string.video_err), Toast.LENGTH_SHORT).show(); } }
From source file:im.vector.fragments.ContactsListDialogFragment.java
/** * Init the dialog view.//w w w . j a va2 s .co m * @param v the dialog view. */ void initView(View v) { mListView = ((ListView) v.findViewById(R.id.listView_contacts)); // get the local contacts mLocalContacts = new ArrayList<Contact>(ContactsManager.getLocalContactsSnapshot(getActivity())); mAdapter = new ContactsListAdapter(getActivity(), R.layout.adapter_item_contact); // sort them Collections.sort(mLocalContacts, alphaComparator); mListView.setFastScrollAlwaysVisible(true); mListView.setFastScrollEnabled(true); mListView.setAdapter(mAdapter); refreshAdapter(); // a button could be added to filter the contacts to display only the matrix users // but the lookup method is too slow (1 address / request). // it could be enabled when a batch request will be implemented /* final Button button = (Button)v.findViewById(R.id.button_matrix_users); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { mDisplayOnlyMatrixUsers = !mDisplayOnlyMatrixUsers; if (mDisplayOnlyMatrixUsers) { button.setBackgroundResource(R.drawable.matrix_user); } else { button.setBackgroundResource(R.drawable.ic_menu_allfriends); } refreshAdapter(); } });*/ final EditText editText = (EditText) v.findViewById(R.id.editText_contactBox); editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(android.text.Editable s) { ContactsListDialogFragment.this.mSearchPattern = s.toString(); refreshAdapter(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); // tap on one of them // if he is a matrix, offer to start a chat // it he is not a matrix user, offer to invite him by email or SMS. mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Contact contact = mAdapter.getItem(position); final Activity activity = ContactsListDialogFragment.this.getActivity(); if (contact.hasMatridIds(ContactsListDialogFragment.this.getActivity())) { final Contact.MXID mxid = contact.getFirstMatrixId(); // The user is trying to leave with unsaved changes. Warn about that new AlertDialog.Builder(activity) .setMessage(activity.getText(R.string.chat_with) + " " + mxid.mMatrixId + " ?") .setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.goToOneToOneRoom(mxid.mAccountId, mxid.mMatrixId, activity, new SimpleApiCallback<Void>(getActivity()) { }); } }); dialog.dismiss(); // dismiss the member list ContactsListDialogFragment.this.dismiss(); } }).setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } else { // invite the user final ArrayList<String> choicesList = new ArrayList<String>(); if (AdapterUtils.canSendSms(activity)) { choicesList.addAll(contact.mPhoneNumbers); } choicesList.addAll(contact.mEmails); // something to offer if (choicesList.size() > 0) { final String[] labels = new String[choicesList.size()]; for (int index = 0; index < choicesList.size(); index++) { labels[index] = choicesList.get(index); } new AlertDialog.Builder(activity).setItems(labels, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String value = labels[which]; // SMS ? if (contact.mPhoneNumbers.indexOf(value) >= 0) { AdapterUtils.launchSmsIntent(activity, value, activity.getString(R.string.invitation_message)); } else { // emails AdapterUtils.launchEmailIntent(activity, value, activity.getString(R.string.invitation_message)); } // dismiss the member list ContactsListDialogFragment.this.dismiss(); } }).setTitle(activity.getString(R.string.invite_this_user_to_use_matrix)).show(); } } } }); }
From source file:jahirfiquitiva.iconshowcase.activities.ViewerActivity.java
private void showApplyWallpaperDialog(final Activity context, final String wallUrl) { ISDialogs.showApplyWallpaperDialog(context, new MaterialDialog.SingleButtonCallback() { @Override//from w ww . j av a 2 s .co m public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { if (dialogApply != null) { dialogApply.dismiss(); } final ApplyWallpaper[] applyTask = new ApplyWallpaper[1]; final boolean[] enteredApplyTask = { false }; dialogApply = new MaterialDialog.Builder(context).content(R.string.downloading_wallpaper) .progress(true, 0).cancelable(false).onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { if (applyTask[0] != null) { applyTask[0].cancel(true); } dialogApply.dismiss(); } }).show(); Glide.with(context).load(wallUrl).asBitmap().diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { if (resource != null && dialogApply.isShowing()) { enteredApplyTask[0] = true; if (dialogApply != null) { dialogApply.dismiss(); } dialogApply = new MaterialDialog.Builder(context) .content(R.string.setting_wall_title).progress(true, 0) .cancelable(false).show(); applyTask[0] = new ApplyWallpaper(context, dialogApply, resource, false, layout, toHide1, toHide2); applyTask[0].execute(); } } }); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUIThread(context, new Runnable() { @Override public void run() { if (!enteredApplyTask[0]) { String newContent = context.getString(R.string.downloading_wallpaper) + "\n" + context.getString(R.string.download_takes_longer); dialogApply.setContent(newContent); dialogApply.setActionButton(DialogAction.POSITIVE, android.R.string.cancel); } } }); } }, 15000); } }, new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { if (!PermissionUtils.canAccessStorage(context)) { PermissionUtils.setViewerActivityAction("crop"); PermissionUtils.requestStoragePermission(context); } else { cropWallpaper(wallUrl); } } }); }
From source file:me.myatminsoe.myansms.Message.java
/** * Get a {@link OnLongClickListener} to save the attachment. * * @param context {@link Context}/*from ww w .j a v a 2 s.c o m*/ * @return {@link OnLongClickListener} */ public OnLongClickListener getSaveAttachmentListener(final Activity context) { if (contentIntent == null) { return null; } return new OnLongClickListener() { @Override public boolean onLongClick(final View v) { // check/request permission Manifest.permission.WRITE_EXTERNAL_STORAGE if (!SMSdroid.requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, 0, R.string.permissions_write_external_storage, null)) { return true; } try { String fn = ATTACHMENT_FILE; final Intent ci = Message.this.contentIntent; final String ct = ci.getType(); if (ct == null) { fn += "null"; } else if (ct.startsWith("image/")) { switch (ct) { case "image/jpeg": fn += "jpg"; break; case "image/gif": fn += "gif"; break; default: fn += "png"; break; } } else if (ct.startsWith("audio/")) { switch (ct) { case "audio/3gpp": fn += "3gpp"; break; case "audio/mpeg": fn += "mp3"; break; case "audio/mid": fn += "mid"; break; default: fn += "wav"; break; } } else if (ct.startsWith("video/")) { if (ct.equals("video/3gpp")) { fn += "3gpp"; } else { fn += "avi"; } } else { fn += "ukn"; } final File file = Message.this.createUniqueFile(Environment.getExternalStorageDirectory(), fn); //noinspection ConstantConditions InputStream in = context.getContentResolver().openInputStream(ci.getData()); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); out.flush(); out.close(); //noinspection ConstantConditions in.close(); Toast.makeText(context, context.getString(R.string.attachment_saved) + " " + fn, Toast.LENGTH_LONG).show(); return true; } catch (IOException e) { Toast.makeText(context, R.string.attachment_not_saved, Toast.LENGTH_LONG).show(); } catch (NullPointerException e) { Toast.makeText(context, R.string.attachment_not_saved, Toast.LENGTH_LONG).show(); } return true; } }; }
From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java
protected AlertDialog.Builder xshowChangeSenderOptions(final Activity act, Bundle args) { final ArrayList<UseContactItem> items = new ArrayList<UseContactItem>(); boolean isContactInUse = args.getBoolean(extra.CREATED); final String pName = args.getString(extra.NAME); byte[] pPhoto = args.getByteArray(extra.PHOTO); String pLookupKey = args.getString(extra.CONTACT_LOOKUP_KEY); if (!TextUtils.isEmpty(pName)) { items.add(new UseContactItem(String.format(act.getString(R.string.menu_UseProfilePerson), pName), pPhoto, pLookupKey, UCType.PROFILE)); }//from www .j a va2 s .c o m int i = 0; String cName = args.getString(extra.NAME + i); byte[] cPhoto = args.getByteArray(extra.PHOTO + i); String cLookupKey = args.getString(extra.CONTACT_LOOKUP_KEY + i); while (!TextUtils.isEmpty(cName)) { items.add(new UseContactItem(String.format(act.getString(R.string.menu_UseContactPerson), cName), cPhoto, cLookupKey, UCType.CONTACT)); i++; cName = args.getString(extra.NAME + i); cPhoto = args.getByteArray(extra.PHOTO + i); cLookupKey = args.getString(extra.CONTACT_LOOKUP_KEY + i); } items.add(new UseContactItem(act.getString(R.string.menu_UseNoContact), UCType.NONE)); items.add(new UseContactItem(act.getString(R.string.menu_UseAnother), UCType.ANOTHER)); items.add(new UseContactItem(act.getString(R.string.menu_CreateNew), UCType.NEW)); items.add(new UseContactItem(act.getString(R.string.menu_EditName), UCType.EDIT_NAME)); if (isContactInUse) { items.add(new UseContactItem(act.getString(R.string.menu_EditContact), UCType.EDIT_CONTACT)); } AlertDialog.Builder ad = new AlertDialog.Builder(act); ad.setTitle(R.string.title_MyIdentity); ad.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); } }); ListAdapter adapter = new ArrayAdapter<UseContactItem>(act, android.R.layout.select_dialog_item, android.R.id.text1, items) { @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); TextView tv = (TextView) v.findViewById(android.R.id.text1); UseContactItem item = items.get(position); if (item.contact) { Drawable d; if (item.icon != null) { Bitmap bm = BitmapFactory.decodeByteArray(item.icon, 0, item.icon.length, null); d = new BitmapDrawable(getResources(), bm); } else { d = getResources().getDrawable(R.drawable.ic_silhouette); } int avatar_size_list = (int) getResources().getDimension(R.dimen.avatar_size_list); d.setBounds(0, 0, avatar_size_list, avatar_size_list); tv.setCompoundDrawables(null, null, d, null); tv.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.size_5dp)); } else { tv.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } return v; } }; ad.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { dialog.dismiss(); switch (items.get(item).type) { case PROFILE: // user wants to use found profile as a personal contact // save these for lookup and display purposes SafeSlingerPrefs.setContactName(pName); SafeSlingerPrefs.setContactLookupKey(items.get(item).contactLookupKey); refreshView(); break; case CONTACT: // user wants to use found contact as a personal contact SafeSlingerPrefs.setContactName(getContactName(items.get(item).contactLookupKey)); SafeSlingerPrefs.setContactLookupKey(items.get(item).contactLookupKey); refreshView(); break; case ANOTHER: // user wants to choose new contact for themselves showPickContact(RESULT_PICK_CONTACT_SENDER); break; case NONE: // user wants to remove link to address book SafeSlingerPrefs.setContactLookupKey(null); refreshView(); break; case NEW: // user wants to create new contact showAddContact(SafeSlingerPrefs.getContactName()); break; case EDIT_CONTACT: // user wants to edit contact showEditContact(RESULT_PICK_CONTACT_SENDER); break; case EDIT_NAME: // user wants to edit name showSettings(); refreshView(); break; } } }); return ad; }
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 w w . j ava 2 s . c om 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 a va 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:jahirfiquitiva.iconshowcase.activities.AltWallpaperViewerActivity.java
private void showApplyWallpaperDialog(final Activity context, final String wallUrl) { ISDialogs.showApplyWallpaperDialog(this, new MaterialDialog.SingleButtonCallback() { @Override/* w w w . j a v a 2 s .c o m*/ public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { if (dialogApply != null) { dialogApply.dismiss(); } if (fabOpened) { closeMenu(); fabOpened = false; } hideFab(fab); final ApplyWallpaper[] applyTask = new ApplyWallpaper[1]; final boolean[] enteredApplyTask = { false }; dialogApply = new MaterialDialog.Builder(AltWallpaperViewerActivity.this) .content(R.string.downloading_wallpaper).progress(true, 0).cancelable(false) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { if (applyTask[0] != null) { applyTask[0].cancel(true); } dialogApply.dismiss(); reshowFab(fab); setupFullScreen(); } }).show(); Glide.with(context).load(wallUrl).asBitmap().dontAnimate() .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { if (resource != null && dialogApply.isShowing()) { enteredApplyTask[0] = true; if (dialogApply != null) { dialogApply.dismiss(); } dialogApply = new MaterialDialog.Builder(context) .content(R.string.setting_wall_title).progress(true, 0) .cancelable(false).show(); applyTask[0] = new ApplyWallpaper(context, resource, new ApplyWallpaper.ApplyCallback() { @Override public void afterApplied() { runOnUIThread(context, new Runnable() { @Override public void run() { if (dialogApply != null) { dialogApply.dismiss(); } dialogApply = new MaterialDialog.Builder(context) .content(R.string.set_as_wall_done) .positiveText(android.R.string.ok).show(); dialogApply.setOnDismissListener( new DialogInterface.OnDismissListener() { @Override public void onDismiss( DialogInterface dialogInterface) { reshowFab(fab); setupFullScreen(); } }); } }); } }); applyTask[0].execute(); } } }); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUIThread(AltWallpaperViewerActivity.this, new Runnable() { @Override public void run() { if (!enteredApplyTask[0]) { String newContent = context.getString(R.string.downloading_wallpaper) + "\n" + context.getString(R.string.download_takes_longer); dialogApply.setContent(newContent); dialogApply.setActionButton(DialogAction.POSITIVE, android.R.string.cancel); } } }); } }, 10000); } }, new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { if (!PermissionUtils.canAccessStorage(AltWallpaperViewerActivity.this)) { PermissionUtils.setViewerActivityAction("crop"); PermissionUtils.requestStoragePermission(AltWallpaperViewerActivity.this); } else { cropWallpaper(wallUrl); } } }, new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { reshowFab(fab); setupFullScreen(); } }); }
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;//from www . j a v a2 s. c om 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; }