List of usage examples for android.app Activity getSystemService
@Override
public Object getSystemService(@ServiceName @NonNull String name)
From source file:com.android.browser.DownloadHandler.java
private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg;/*from w ww . j a va2 s . c o m*/ // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = activity.getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(msg).setPositiveButton(R.string.ok, null).show(); return; } // java.net.URI is a lot stricter than KURL so we have to encode some // extra characters. Fix for b 2538060 and b 1634719 WebAddress webAddress; try { webAddress = new WebAddress(url); webAddress.setPath(encodePath(webAddress.getPath())); } catch (Exception e) { // This only happens for very bad urls, we want to chatch the // exception here Log.e(LOGTAG, "Exception trying to parse url:" + url); return; } String addressString = webAddress.toString(); Uri uri = Uri.parse(addressString); final DownloadManager.Request request; try { request = new DownloadManager.Request(uri); } catch (IllegalArgumentException e) { Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show(); return; } request.setMimeType(mimetype); // set downloaded file destination to /sdcard/Download. // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype? try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); } catch (IllegalStateException ex) { // This only happens when directory Downloads can't be created or it isn't a directory // this is most commonly due to temporary problems with sdcard so show appropriate string Log.w(LOGTAG, "Exception trying to create Download dir:", ex); Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show(); return; } // let this downloaded file be scanned by MediaScanner - so that it can // show up in Gallery app, for example. request.allowScanningByMediaScanner(); request.setDescription(webAddress.getHost()); // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); if (!TextUtils.isEmpty(referer)) { request.addRequestHeader("Referer", referer); } request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (mimetype == null) { if (TextUtils.isEmpty(addressString)) { return; } // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start(); } else { final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); new Thread("Browser download") { public void run() { manager.enqueue(request); } }.start(); } Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show(); }
From source file:com.android.stockbrowser.DownloadHandler.java
private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg;// w ww. j a v a 2 s. c o m // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = activity.getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(msg).setPositiveButton(R.string.ok, null).show(); return; } // java.net.URI is a lot stricter than KURL so we have to encode some // extra characters. Fix for b 2538060 and b 1634719 WebAddress webAddress; try { webAddress = new WebAddress(url); webAddress.setPath(encodePath(webAddress.getPath())); } catch (Exception e) { // This only happens for very bad urls, we want to chatch the // exception here Log.e(LOGTAG, "Exception trying to parse url:" + url); return; } String addressString = webAddress.toString(); Uri uri = Uri.parse(addressString); final DownloadManager.Request request; try { request = new DownloadManager.Request(uri); } catch (IllegalArgumentException e) { Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show(); return; } request.setMimeType(mimetype); // set downloaded file destination to /sdcard/Download. // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype? try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); } catch (IllegalStateException ex) { // This only happens when directory Downloads can't be created or it isn't a directory // this is most commonly due to temporary problems with sdcard so show appropriate string Log.w(LOGTAG, "Exception trying to create Download dir:", ex); Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show(); return; } // let this downloaded file be scanned by MediaScanner - so that it can // show up in Gallery app, for example. request.allowScanningByMediaScanner(); request.setDescription(webAddress.getHost()); // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = "";//CookieManager.getInstance().getCookie(url, privateBrowsing); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); if (!TextUtils.isEmpty(referer)) { request.addRequestHeader("Referer", referer); } request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (mimetype == null) { if (TextUtils.isEmpty(addressString)) { return; } // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start(); } else { final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); new Thread("StockBrowser download") { public void run() { manager.enqueue(request); } }.start(); } Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show(); }
From source file:com.sabaibrowser.DownloadHandler.java
private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent, String contentDisposition, String mimetype, String referer, boolean privateBrowsing) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg;//from w w w. j av a2 s. c om // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = activity.getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon) .setMessage(msg).setPositiveButton(R.string.ok, null).show(); return; } // java.net.URI is a lot stricter than KURL so we have to encode some // extra characters. Fix for b 2538060 and b 1634719 WebAddress webAddress; try { webAddress = new WebAddress(url); webAddress.setPath(encodePath(webAddress.getPath())); } catch (Exception e) { // This only happens for very bad urls, we want to chatch the // exception here Log.e(LOGTAG, "Exception trying to parse url:" + url); return; } String addressString = webAddress.toString(); Uri uri = Uri.parse(addressString); final DownloadManager.Request request; try { request = new DownloadManager.Request(uri); } catch (IllegalArgumentException e) { Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show(); return; } request.setMimeType(mimetype); // set downloaded file destination to /sdcard/Download. // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype? try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); } catch (IllegalStateException ex) { // This only happens when directory Downloads can't be created or it isn't a directory // this is most commonly due to temporary problems with sdcard so show appropriate string Log.w(LOGTAG, "Exception trying to create Download dir:", ex); Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show(); return; } // let this downloaded file be scanned by MediaScanner - so that it can // show up in Gallery app, for example. request.allowScanningByMediaScanner(); request.setDescription(webAddress.getHost()); // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = privateBrowsing ? "" : CookieManager.getInstance().getCookie(url); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); if (!TextUtils.isEmpty(referer)) { request.addRequestHeader("Referer", referer); } request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (mimetype == null) { if (TextUtils.isEmpty(addressString)) { return; } // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start(); } else { final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE); new Thread("Browser download") { public void run() { manager.enqueue(request); } }.start(); } Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show(); }
From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java
private AlertDialog.Builder xshowManagePassphrases(final Activity act, Bundle args) { String msg = args.getString(extra.RESID_MSG); boolean allowDelete = args.getBoolean(extra.ALLOW_DELETE); AlertDialog.Builder ad = new AlertDialog.Builder(act); View layout;//from w w w . j a v a 2 s . c o m if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { layout = View.inflate(new ContextThemeWrapper(act, R.style.Theme_AppCompat), R.layout.about, null); } else { LayoutInflater inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE); layout = inflater.inflate(R.layout.about, null); } TextView textViewAbout = (TextView) layout.findViewById(R.id.TextViewAbout); ad.setTitle(R.string.menu_ManagePassphrases); textViewAbout.setText(msg); ad.setView(layout); ad.setCancelable(true); if (allowDelete) { // only have delete key when recent keys exist ad.setPositiveButton(R.string.btn_DeleteKeys, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // delete all more recent keys for now... doRemoveMoreRecentKeys(); refreshView(); } }); } ad.setNegativeButton(R.string.btn_Cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); } }); return ad; }
From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java
private AlertDialog.Builder xshowIntroductionInvite(final Activity act, final Bundle args) { String exchName = args.getString(extra.EXCH_NAME); final String introName = args.getString(extra.INTRO_NAME); final byte[] introPhoto = args.getByteArray(extra.PHOTO); final byte[] introPush = args.getByteArray(extra.PUSH_REGISTRATION_ID); final byte[] introPubKey = args.getByteArray(extra.INTRO_PUBKEY); final long msgRowId = args.getLong(extra.MESSAGE_ROW_ID); AlertDialog.Builder ad = new AlertDialog.Builder(act); View layout;/*from w w w . j a va 2 s. c o m*/ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { layout = View.inflate(new ContextThemeWrapper(act, R.style.Theme_AppCompat), R.layout.secureinvite, null); } else { LayoutInflater inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE); layout = inflater.inflate(R.layout.secureinvite, null); } TextView textViewExchName = (TextView) layout.findViewById(R.id.textViewExchName); TextView textViewIntroName = (TextView) layout.findViewById(R.id.textViewIntroName); ImageView imageViewIntroPhoto = (ImageView) layout.findViewById(R.id.imageViewIntroPhoto); ad.setTitle(R.string.title_SecureIntroductionInvite); textViewExchName.setText(exchName); textViewIntroName.setText(introName); if (introPhoto != null) { try { Bitmap bm = BitmapFactory.decodeByteArray(introPhoto, 0, introPhoto.length, null); imageViewIntroPhoto.setImageBitmap(bm); } catch (OutOfMemoryError e) { imageViewIntroPhoto.setImageDrawable(getResources().getDrawable(R.drawable.ic_silhouette)); } } ad.setView(layout); ad.setCancelable(false); ad.setPositiveButton(getString(R.string.btn_Accept), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // accept secure introduction? int selected = 0; args.putString(extra.NAME + selected, introName); args.putByteArray(extra.PHOTO + selected, introPhoto); args.putByteArray(SafeSlingerConfig.APP_KEY_PUBKEY + selected, introPubKey); args.putByteArray(SafeSlingerConfig.APP_KEY_PUSHTOKEN + selected, introPush); String contactLookupKey = getContactLookupKeyByName(introName); args.putString(extra.CONTACT_LOOKUP_KEY + selected, contactLookupKey); MessageRow inviteMsg = null; MessageDbAdapter dbMessage = MessageDbAdapter.openInstance(getApplicationContext()); Cursor c = dbMessage.fetchMessageSmall(msgRowId); if (c != null) { try { if (c.moveToFirst()) { inviteMsg = new MessageRow(c, false); } } finally { c.close(); } } if (inviteMsg == null) { showNote(R.string.error_InvalidIncomingMessage); return; } // import the new contacts args.putInt(extra.RECIP_SOURCE, RecipientDbAdapter.RECIP_SOURCE_INTRODUCTION); args.putString(extra.KEYID, inviteMsg.getKeyId()); ImportFromExchangeTask importFromExchange = new ImportFromExchangeTask(); importFromExchange.execute(args); setTab(Tabs.MESSAGE); refreshView(); } }); ad.setNegativeButton(getString(R.string.btn_Refuse), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); showNote(String.format(getString(R.string.state_SomeContactsImported), 0)); refreshView(); } }); return ad; }
From source file:de.anderdonau.spacetrader.Main.java
public static void hide_keyboard(Activity activity) { // https://stackoverflow.com/a/17789187 InputMethodManager inputMethodManager = (InputMethodManager) activity .getSystemService(INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. View view = activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); }// w w w. jav a2s. c o m inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); }
From source file:carnero.cgeo.original.libs.Base.java
public void storeCache(App app, Activity activity, Cache cache, String geocode, int listId, Handler handler) { try {/*from w ww.jav a 2 s . co m*/ // cache details if (cache != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("geocode", cache.geocode); final Long searchId = searchByGeocode(params, listId, false); cache = app.getCache(searchId); } else if (geocode != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("geocode", geocode); final Long searchId = searchByGeocode(params, listId, false); cache = app.getCache(searchId); } if (cache == null) { if (handler != null) { handler.sendMessage(new Message()); } return; } final HtmlImg imgGetter = new HtmlImg(activity, settings, cache.geocode, false, listId, true); // store images from description if (cache.description != null) { Html.fromHtml(cache.description, imgGetter, null); } // store spoilers if (cache.spoilers != null && cache.spoilers.isEmpty() == false) { for (Spoiler oneSpoiler : cache.spoilers) { imgGetter.getDrawable(oneSpoiler.url); } } // store map previews if (settings.storeOfflineMaps == 1 && cache.latitude != null && cache.longitude != null) { final String latlonMap = String.format((Locale) null, "%.6f", cache.latitude) + "," + String.format((Locale) null, "%.6f", cache.longitude); final Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; int edge = 0; if (maxWidth > maxHeight) { edge = maxWidth; } else { edge = maxHeight; } String type = "mystery"; if (cache.found == true) { type = cache.type + "_found"; } else if (cache.disabled == true) { type = cache.type + "_disabled"; } else { type = cache.type; } final String markerUrl = urlencode_rfc3986( "http://cgeo.carnero.cc/_markers/marker_cache_" + type + ".png"); final StringBuilder waypoints = new StringBuilder(); if (cache.waypoints != null && cache.waypoints.size() > 0) { for (Waypoint waypoint : cache.waypoints) { if (waypoint.latitude == null && waypoint.longitude == null) { continue; } waypoints.append("&markers=icon%3Ahttp://cgeo.carnero.cc/_markers/marker_waypoint_"); waypoints.append(waypoint.type); waypoints.append(".png%7C"); waypoints.append(String.format((Locale) null, "%.6f", waypoint.latitude)); waypoints.append(","); waypoints.append(String.format((Locale) null, "%.6f", waypoint.longitude)); } } // download map images in separate background thread for higher performance final String code = cache.geocode; final int finalEdge = edge; Thread staticMapsThread = new Thread("getting static map") { @Override public void run() { MapImg mapGetter = new MapImg(settings, code); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=20&size=" + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 1); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=18&size=" + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 2); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=16&size=" + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 3); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=14&size=" + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 4); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=11&size=" + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 5); } }; staticMapsThread.setPriority(Thread.MIN_PRIORITY); staticMapsThread.start(); } app.markStored(cache.geocode, listId); app.removeCacheFromCache(cache.geocode); if (handler != null) { handler.sendMessage(new Message()); } } catch (Exception e) { Log.e(Settings.tag, "cgBase.storeCache: " + e.toString()); } }
From source file:carnero.cgeo.cgBase.java
public void storeCache(cgeoapplication app, Activity activity, cgCache cache, String geocode, int listId, Handler handler) {//from w w w.jav a 2 s. c om try { // cache details if (cache != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("geocode", cache.geocode); final Long searchId = searchByGeocode(params, listId, false); cache = app.getCache(searchId); } else if (geocode != null) { final HashMap<String, String> params = new HashMap<String, String>(); params.put("geocode", geocode); final Long searchId = searchByGeocode(params, listId, false); cache = app.getCache(searchId); } if (cache == null) { if (handler != null) { handler.sendMessage(new Message()); } return; } final cgHtmlImg imgGetter = new cgHtmlImg(activity, settings, cache.geocode, false, listId, true); // store images from description if (cache.description != null) { Html.fromHtml(cache.description, imgGetter, null); } // store spoilers if (cache.spoilers != null && cache.spoilers.isEmpty() == false) { for (cgSpoiler oneSpoiler : cache.spoilers) { imgGetter.getDrawable(oneSpoiler.url); } } // store map previews if (settings.storeOfflineMaps == 1 && cache.latitude != null && cache.longitude != null) { final String latlonMap = String.format((Locale) null, "%.6f", cache.latitude) + "," + String.format((Locale) null, "%.6f", cache.longitude); final Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; int edge = 0; if (maxWidth > maxHeight) { edge = maxWidth; } else { edge = maxHeight; } String type = "mystery"; if (cache.found == true) { type = cache.type + "_found"; } else if (cache.disabled == true) { type = cache.type + "_disabled"; } else { type = cache.type; } final String markerUrl = urlencode_rfc3986( "http://cgeo.carnero.cc/_markers/marker_cache_" + type + ".png"); final StringBuilder waypoints = new StringBuilder(); if (cache.waypoints != null && cache.waypoints.size() > 0) { for (cgWaypoint waypoint : cache.waypoints) { if (waypoint.latitude == null && waypoint.longitude == null) { continue; } waypoints.append("&markers=icon%3Ahttp://cgeo.carnero.cc/_markers/marker_waypoint_"); waypoints.append(waypoint.type); waypoints.append(".png%7C"); waypoints.append(String.format((Locale) null, "%.6f", waypoint.latitude)); waypoints.append(","); waypoints.append(String.format((Locale) null, "%.6f", waypoint.longitude)); } } // download map images in separate background thread for higher performance final String code = cache.geocode; final int finalEdge = edge; Thread staticMapsThread = new Thread("getting static map") { @Override public void run() { cgMapImg mapGetter = new cgMapImg(settings, code); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=20&size=" + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 1); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=18&size=" + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 2); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=16&size=" + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 3); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=14&size=" + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 4); mapGetter.getDrawable( "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=11&size=" + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false", 5); } }; staticMapsThread.setPriority(Thread.MIN_PRIORITY); staticMapsThread.start(); } app.markStored(cache.geocode, listId); app.removeCacheFromCache(cache.geocode); if (handler != null) { handler.sendMessage(new Message()); } } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.storeCache: " + e.toString()); } }
From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java
public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity, final Action action) { switch (action) { case UPVOTE:// w w w . j av a2 s .co m post.action(activity, RedditAPI.RedditAction.UPVOTE); break; case DOWNVOTE: post.action(activity, RedditAPI.RedditAction.DOWNVOTE); break; case UNVOTE: post.action(activity, RedditAPI.RedditAction.UNVOTE); break; case SAVE: post.action(activity, RedditAPI.RedditAction.SAVE); break; case UNSAVE: post.action(activity, RedditAPI.RedditAction.UNSAVE); break; case HIDE: post.action(activity, RedditAPI.RedditAction.HIDE); break; case UNHIDE: post.action(activity, RedditAPI.RedditAction.UNHIDE); break; case DELETE: new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm) .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.RedditAction.DELETE); } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case REPORT: new AlertDialog.Builder(activity).setTitle(R.string.action_report) .setMessage(R.string.action_report_sure) .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.RedditAction.REPORT); // TODO update the view to show the result // TODO don't forget, this also hides } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case EXTERNAL: { final Intent intent = new Intent(Intent.ACTION_VIEW); String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl() : post.url; intent.setData(Uri.parse(url)); activity.startActivity(intent); break; } case SELFTEXT_LINKS: { final HashSet<String> linksInComment = LinkHandler .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext)); if (linksInComment.isEmpty()) { General.quickToast(activity, R.string.error_toast_no_urls_in_self); } else { final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setItems(linksArr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src); dialog.dismiss(); } }); final AlertDialog alert = builder.create(); alert.setTitle(R.string.action_selftext_links); alert.setCanceledOnTouchOutside(true); alert.show(); } break; } case SAVE_IMAGE: { final RedditAccount anon = RedditAccountManager.getAnon(); LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0, new GetImageInfoListener() { @Override public void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status, final String readableMessage) { final RRError error = General.getGeneralErrorForFailure(activity, type, t, status, post.url); General.showResultDialog(activity, error); } @Override public void onSuccess(final ImgurAPI.ImageInfo info) { CacheManager.getInstance(activity) .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon, null, Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY, Constants.FileType.IMAGE, false, false, false, activity) { @Override protected void onCallbackException(Throwable t) { BugReportActivity.handleGlobalError(context, t); } @Override protected void onDownloadNecessary() { General.quickToast(context, R.string.download_downloading); } @Override protected void onDownloadStarted() { } @Override protected void onFailure(RequestFailureType type, Throwable t, StatusLine status, String readableMessage) { final RRError error = General.getGeneralErrorForFailure(context, type, t, status, url.toString()); General.showResultDialog(activity, error); } @Override protected void onProgress(boolean authorizationInProgress, long bytesRead, long totalBytes) { } @Override protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp, UUID session, boolean fromCache, String mimetype) { File dst = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), General.uriFromString(info.urlOriginal).getPath()); if (dst.exists()) { int count = 0; while (dst.exists()) { count++; dst = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), count + "_" + General.uriFromString(info.urlOriginal) .getPath().substring(1)); } } try { final InputStream cacheFileInputStream = cacheFile.getInputStream(); if (cacheFileInputStream == null) { notifyFailure(RequestFailureType.CACHE_MISS, null, null, "Could not find cached image"); return; } General.copyFile(cacheFileInputStream, dst); } catch (IOException e) { notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file"); return; } activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dst.getAbsolutePath()))); General.quickToast(context, context.getString(R.string.action_save_image_success) + " " + dst.getAbsolutePath()); } }); } @Override public void onNotAnImage() { General.quickToast(activity, R.string.selected_link_is_not_image); } }); break; } case SHARE: { final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, post.title); mailer.putExtra(Intent.EXTRA_TEXT, post.url); activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share))); break; } case SHARE_COMMENTS: { final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title); mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString()); activity.startActivity( Intent.createChooser(mailer, activity.getString(R.string.action_share_comments))); break; } case COPY: { ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); manager.setText(post.url); break; } case GOTO_SUBREDDIT: { try { final Intent intent = new Intent(activity, PostListingActivity.class); intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri()); activity.startActivityForResult(intent, 1); } catch (RedditSubreddit.InvalidSubredditNameException e) { Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show(); } break; } case USER_PROFILE: LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString()); break; case PROPERTIES: PostPropertiesDialog.newInstance(post.src).show(activity.getFragmentManager(), null); break; case COMMENTS: ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post); break; case LINK: ((RedditPostView.PostSelectionListener) activity).onPostSelected(post); break; case COMMENTS_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post); break; case LINK_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((RedditPostView.PostSelectionListener) activity).onPostSelected(post); break; case ACTION_MENU: showActionMenu(activity, post); break; case REPLY: final Intent intent = new Intent(activity, CommentReplyActivity.class); intent.putExtra("parentIdAndType", post.idAndType); activity.startActivity(intent); break; } }