List of usage examples for android.net Uri getPathSegments
public abstract List<String> getPathSegments();
From source file:org.matrix.console.activity.RoomActivity.java
/** * Send a list of images from their URIs * @param mediaUris the media URIs//from ww w.j a va2s. c o m */ private void sendMedias(final ArrayList<Uri> mediaUris) { final View progressBackground = findViewById(R.id.medias_processing_progress_background); final View progress = findViewById(R.id.medias_processing_progress); progressBackground.setVisibility(View.VISIBLE); progress.setVisibility(View.VISIBLE); final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread"); handlerThread.start(); final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper()); Runnable r = new Runnable() { @Override public void run() { handler.post(new Runnable() { public void run() { final int mediaCount = mediaUris.size(); for (Uri anUri : mediaUris) { // crash from Google Analytics : null URI on a nexus 5 if (null != anUri) { final Uri mediaUri = anUri; String filename = null; if (mediaUri.toString().startsWith("content://")) { Cursor cursor = null; try { cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { filename = cursor .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } catch (Exception e) { Log.e(LOG_TAG, "cursor.getString " + e.getMessage()); } finally { if (null != cursor) { cursor.close(); } } if (TextUtils.isEmpty(filename)) { List uriPath = mediaUri.getPathSegments(); filename = (String) uriPath.get(uriPath.size() - 1); } } else if (mediaUri.toString().startsWith("file://")) { // try to retrieve the filename from the file url. try { filename = anUri.getLastPathSegment(); } catch (Exception e) { } if (TextUtils.isEmpty(filename)) { filename = null; } } final String fFilename = filename; ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this, mediaUri); if (null == resource) { RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { handlerThread.quit(); progressBackground.setVisibility(View.GONE); progress.setVisibility(View.GONE); Toast.makeText(RoomActivity.this, getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG) .show(); } ; }); return; } // save the file in the filesystem String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null, resource.mimeType); String mimeType = resource.mimeType; Boolean isManaged = false; if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) { // manage except if there is an error isManaged = true; // try to retrieve the gallery thumbnail // if the image comes from the gallery.. Bitmap thumbnailBitmap = null; try { ContentResolver resolver = getContentResolver(); List uriPath = mediaUri.getPathSegments(); long imageId = -1; String lastSegment = (String) uriPath.get(uriPath.size() - 1); // > Kitkat if (lastSegment.startsWith("image:")) { lastSegment = lastSegment.substring("image:".length()); } imageId = Long.parseLong(lastSegment); thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null); } catch (Exception e) { Log.e(LOG_TAG, "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage()); } double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith(); double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight(); // no thumbnail has been found or the mimetype is unknown if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight) || (thumbnailBitmap.getWidth() > thumbnailWidth)) { // need to decompress the high res image BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; resource = ResourceUtils.openResource(RoomActivity.this, mediaUri); // get the full size bitmap Bitmap fullSizeBitmap = null; if (null == thumbnailBitmap) { fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream, null, options); } if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) { double imageWidth; double imageHeight; if (null == thumbnailBitmap) { imageWidth = fullSizeBitmap.getWidth(); imageHeight = fullSizeBitmap.getHeight(); } else { imageWidth = thumbnailBitmap.getWidth(); imageHeight = thumbnailBitmap.getHeight(); } if (imageWidth > imageHeight) { thumbnailHeight = thumbnailWidth * imageHeight / imageWidth; } else { thumbnailWidth = thumbnailHeight * imageWidth / imageHeight; } try { thumbnailBitmap = Bitmap.createScaledBitmap( (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap, (int) thumbnailWidth, (int) thumbnailHeight, false); } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage()); } } // the valid mimetype is not provided if ("image/*".equals(mimeType)) { // make a jpg snapshot. mimeType = null; } // unknown mimetype if ((null == mimeType) || (mimeType.startsWith("image/"))) { try { // try again if (null == fullSizeBitmap) { System.gc(); fullSizeBitmap = BitmapFactory .decodeStream(resource.contentStream, null, options); } if (null != fullSizeBitmap) { Uri uri = Uri.parse(mediaUrl); if (null == mimeType) { // the images are save in jpeg format mimeType = "image/jpeg"; } resource.contentStream.close(); resource = ResourceUtils.openResource(RoomActivity.this, mediaUri); try { mMediasCache.saveMedia(resource.contentStream, uri.getPath(), mimeType); } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage()); } } else { isManaged = false; } resource.contentStream.close(); } catch (Exception e) { isManaged = false; Log.e(LOG_TAG, "sendMedias " + e.getMessage()); } } // reduce the memory consumption if (null != fullSizeBitmap) { fullSizeBitmap.recycle(); System.gc(); } } String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null); if (null != thumbnailBitmap) { thumbnailBitmap.recycle(); } // if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType)) && (null != mediaUrl)) { Uri imageUri = Uri.parse(mediaUrl); // get the exif rotation angle final int rotationAngle = ImageUtils .getRotationAngleForBitmap(RoomActivity.this, imageUri); if (0 != rotationAngle) { // always apply the rotation to the image ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle, mMediasCache); // the high res media orientation should be not be done on uploading //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache)) } } // is the image content valid ? if (isManaged && (null != thumbnailURL)) { final String fThumbnailURL = thumbnailURL; final String fMediaUrl = mediaUrl; final String fMimeType = mimeType; RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // if there is only one image if (mediaCount == 1) { // display an image preview before sending it mPendingThumbnailUrl = fThumbnailURL; mPendingMediaUrl = fMediaUrl; mPendingMimeType = fMimeType; mPendingFilename = fFilename; mConsoleMessageListFragment.scrollToBottom(); manageSendMoreButtons(); } else { mConsoleMessageListFragment.uploadImageContent(fThumbnailURL, fMediaUrl, fFilename, fMimeType); } } }); } } // default behaviour if ((!isManaged) && (null != mediaUrl)) { final String fMediaUrl = mediaUrl; final String fMimeType = mimeType; RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if ((null != fMimeType) && fMimeType.startsWith("video/")) { mConsoleMessageListFragment.uploadVideoContent(fMediaUrl, null, fMimeType); } else { mConsoleMessageListFragment.uploadFileContent(fMediaUrl, fMimeType, fFilename); } } }); } } } RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { handlerThread.quit(); progressBackground.setVisibility(View.GONE); progress.setVisibility(View.GONE); }; }); } }); } }; Thread t = new Thread(r); t.start(); }
From source file:com.irccloud.android.activity.MainActivity.java
private boolean open_uri(Uri uri) { if (uri != null && conn != null && conn.ready) { launchURI = null;//w ww .j a v a 2 s.c o m ServersDataSource.Server s = null; try { if (uri.getHost().equals("cid")) { s = ServersDataSource.getInstance().getServer(Integer.parseInt(uri.getPathSegments().get(0))); } } catch (NumberFormatException e) { } if (s == null) { if (uri.getPort() > 0) s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort()); else if (uri.getScheme() != null && uri.getScheme().equalsIgnoreCase("ircs")) s = ServersDataSource.getInstance().getServer(uri.getHost(), true); else s = ServersDataSource.getInstance().getServer(uri.getHost()); } if (s != null) { if (uri.getPath() != null && uri.getPath().length() > 1) { String key = null; String channel = uri.getLastPathSegment(); if (channel.contains(",")) { key = channel.substring(channel.indexOf(",") + 1); channel = channel.substring(0, channel.indexOf(",")); } BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel); if (b != null) { server = null; return open_bid(b.bid); } else { onBufferSelected(-1); title.setText(channel); getSupportActionBar().setTitle(channel); bufferToOpen = channel; conn.join(s.cid, channel, key); } return true; } else { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*"); if (b != null) return open_bid(b.bid); } } else { if (!getResources().getBoolean(R.bool.isTablet)) { Intent i = new Intent(this, EditConnectionActivity.class); i.putExtra("hostname", uri.getHost()); if (uri.getPort() > 0) i.putExtra("port", uri.getPort()); else if (uri.getScheme().equalsIgnoreCase("ircs")) i.putExtra("port", 6697); if (uri.getPath() != null && uri.getPath().length() > 1) i.putExtra("channels", uri.getPath().substring(1).replace(",", " ")); startActivity(i); } else { EditConnectionFragment connFragment = new EditConnectionFragment(); connFragment.default_hostname = uri.getHost(); if (uri.getPort() > 0) connFragment.default_port = uri.getPort(); else if (uri.getScheme().equalsIgnoreCase("ircs")) connFragment.default_port = 6697; if (uri.getPath() != null && uri.getPath().length() > 1) connFragment.default_channels = uri.getPath().substring(1).replace(",", " "); connFragment.show(getSupportFragmentManager(), "addnetwork"); } return true; } } return false; }
From source file:org.cafemember.ui.LaunchActivity.java
private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) { int flags = intent.getFlags(); if (!fromPassword && (AndroidUtilities.needShowPasscode(true) || UserConfig.isWaitingForPasscodeEnter)) { showPasscodeActivity();/*from w ww . ja v a 2 s . c o m*/ passcodeSaveIntent = intent; passcodeSaveIntentIsNew = isNew; passcodeSaveIntentIsRestore = restore; UserConfig.saveConfig(false); } else { boolean pushOpened = false; Integer push_user_id = 0; Integer push_chat_id = 0; Integer push_enc_id = 0; Integer open_settings = 0; long dialogId = intent != null && intent.getExtras() != null ? intent.getExtras().getLong("dialogId", 0) : 0; boolean showDialogsList = false; boolean showPlayer = false; photoPathsArray = null; videoPath = null; sendingText = null; documentsPathsArray = null; documentsOriginalPathsArray = null; documentsMimeType = null; documentsUrisArray = null; contactsToSend = null; if (UserConfig.isClientActivated() && (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if (intent != null && intent.getAction() != null && !restore) { if (Intent.ACTION_SEND.equals(intent.getAction())) { boolean error = false; String type = intent.getType(); if (type != null && type.equals(ContactsContract.Contacts.CONTENT_VCARD_TYPE)) { try { Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM); if (uri != null) { ContentResolver cr = getContentResolver(); InputStream stream = cr.openInputStream(uri); String name = null; String nameEncoding = null; String nameCharset = null; ArrayList<String> phones = new ArrayList<>(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(stream, "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { String[] args = line.split(":"); if (args.length != 2) { continue; } if (args[0].startsWith("FN")) { String[] params = args[0].split(";"); for (String param : params) { String[] args2 = param.split("="); if (args2.length != 2) { continue; } if (args2[0].equals("CHARSET")) { nameCharset = args2[1]; } else if (args2[0].equals("ENCODING")) { nameEncoding = args2[1]; } } name = args[1]; if (nameEncoding != null && nameEncoding.equalsIgnoreCase("QUOTED-PRINTABLE")) { while (name.endsWith("=") && nameEncoding != null) { name = name.substring(0, name.length() - 1); line = bufferedReader.readLine(); if (line == null) { break; } name += line; } byte[] bytes = AndroidUtilities .decodeQuotedPrintable(name.getBytes()); if (bytes != null && bytes.length != 0) { String decodedName = new String(bytes, nameCharset); if (decodedName != null) { name = decodedName; } } } } else if (args[0].startsWith("TEL")) { String phone = PhoneFormat.stripExceptNumbers(args[1], true); if (phone.length() > 0) { phones.add(phone); } } } try { bufferedReader.close(); stream.close(); } catch (Exception e) { FileLog.e("tmessages", e); } if (name != null && !phones.isEmpty()) { contactsToSend = new ArrayList<>(); for (String phone : phones) { TLRPC.User user = new TLRPC.TL_userContact_old2(); user.phone = phone; user.first_name = name; user.last_name = ""; user.id = 0; contactsToSend.add(user); } } } else { error = true; } } catch (Exception e) { FileLog.e("tmessages", e); error = true; } } else { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text == null) { CharSequence textSequence = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); if (textSequence != null) { text = textSequence.toString(); } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (text != null && text.length() != 0) { if ((text.startsWith("http://") || text.startsWith("https://")) && subject != null && subject.length() != 0) { text = subject + "\n" + text; } sendingText = text; } else if (subject != null && subject.length() > 0) { sendingText = subject; } Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (parcelable != null) { String path; if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } Uri uri = (Uri) parcelable; if (uri != null) { if (isInternalUri(uri)) { error = true; } } if (!error) { if (uri != null && (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg"))) { if (photoPathsArray == null) { photoPathsArray = new ArrayList<>(); } photoPathsArray.add(uri); } else { path = AndroidUtilities.getPath(uri); if (path != null) { if (path.startsWith("file:")) { path = path.replace("file://", ""); } if (type != null && type.startsWith("video/")) { videoPath = path; } else { if (documentsPathsArray == null) { documentsPathsArray = new ArrayList<>(); documentsOriginalPathsArray = new ArrayList<>(); } documentsPathsArray.add(path); documentsOriginalPathsArray.add(uri.toString()); } } else { if (documentsUrisArray == null) { documentsUrisArray = new ArrayList<>(); } documentsUrisArray.add(uri); documentsMimeType = type; } } if (sendingText != null) { if (sendingText.contains("WhatsApp")) { //remove unnecessary caption 'sent from WhatsApp' from photos forwarded from WhatsApp sendingText = null; } } } } else if (sendingText == null) { error = true; } } if (error) { Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show(); } } else if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { boolean error = false; try { ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); String type = intent.getType(); if (uris != null) { for (int a = 0; a < uris.size(); a++) { Parcelable parcelable = uris.get(a); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } Uri uri = (Uri) parcelable; if (uri != null) { if (isInternalUri(uri)) { uris.remove(a); a--; } } } if (uris.isEmpty()) { uris = null; } } if (uris != null) { if (type != null && type.startsWith("image/")) { for (int a = 0; a < uris.size(); a++) { Parcelable parcelable = uris.get(a); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } Uri uri = (Uri) parcelable; if (photoPathsArray == null) { photoPathsArray = new ArrayList<>(); } photoPathsArray.add(uri); } } else { for (int a = 0; a < uris.size(); a++) { Parcelable parcelable = uris.get(a); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } String path = AndroidUtilities.getPath((Uri) parcelable); String originalPath = parcelable.toString(); if (originalPath == null) { originalPath = path; } if (path != null) { if (path.startsWith("file:")) { path = path.replace("file://", ""); } if (documentsPathsArray == null) { documentsPathsArray = new ArrayList<>(); documentsOriginalPathsArray = new ArrayList<>(); } documentsPathsArray.add(path); documentsOriginalPathsArray.add(originalPath); } } } } else { error = true; } } catch (Exception e) { FileLog.e("tmessages", e); error = true; } if (error) { Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show(); } } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { Uri data = intent.getData(); if (data != null) { String username = null; String group = null; String sticker = null; String botUser = null; String botChat = null; String message = null; Integer messageId = null; boolean hasUrl = false; String scheme = data.getScheme(); if (scheme != null) { if ((scheme.equals("http") || scheme.equals("https"))) { String host = data.getHost().toLowerCase(); if (host.equals("telegram.me") || host.equals("telegram.dog")) { String path = data.getPath(); if (path != null && path.length() > 1) { path = path.substring(1); if (path.startsWith("joinchat/")) { group = path.replace("joinchat/", ""); } else if (path.startsWith("addstickers/")) { sticker = path.replace("addstickers/", ""); } else if (path.startsWith("msg/") || path.startsWith("share/")) { message = data.getQueryParameter("url"); if (message == null) { message = ""; } if (data.getQueryParameter("text") != null) { if (message.length() > 0) { hasUrl = true; message += "\n"; } message += data.getQueryParameter("text"); } } else if (path.length() >= 1) { List<String> segments = data.getPathSegments(); if (segments.size() > 0) { username = segments.get(0); if (segments.size() > 1) { messageId = Utilities.parseInt(segments.get(1)); if (messageId == 0) { messageId = null; } } } botUser = data.getQueryParameter("start"); botChat = data.getQueryParameter("startgroup"); } } } } else if (scheme.equals("tg")) { String url = data.toString(); if (url.startsWith("tg:resolve") || url.startsWith("tg://resolve")) { url = url.replace("tg:resolve", "tg://telegram.org").replace("tg://resolve", "tg://telegram.org"); data = Uri.parse(url); username = data.getQueryParameter("domain"); botUser = data.getQueryParameter("start"); botChat = data.getQueryParameter("startgroup"); } else if (url.startsWith("tg:join") || url.startsWith("tg://join")) { url = url.replace("tg:join", "tg://telegram.org").replace("tg://join", "tg://telegram.org"); data = Uri.parse(url); group = data.getQueryParameter("invite"); } else if (url.startsWith("tg:addstickers") || url.startsWith("tg://addstickers")) { url = url.replace("tg:addstickers", "tg://telegram.org") .replace("tg://addstickers", "tg://telegram.org"); data = Uri.parse(url); sticker = data.getQueryParameter("set"); } else if (url.startsWith("tg:msg") || url.startsWith("tg://msg") || url.startsWith("tg://share") || url.startsWith("tg:share")) { url = url.replace("tg:msg", "tg://telegram.org") .replace("tg://msg", "tg://telegram.org") .replace("tg://share", "tg://telegram.org") .replace("tg:share", "tg://telegram.org"); data = Uri.parse(url); message = data.getQueryParameter("url"); if (message == null) { message = ""; } if (data.getQueryParameter("text") != null) { if (message.length() > 0) { hasUrl = true; message += "\n"; } message += data.getQueryParameter("text"); } } } } if (username != null || group != null || sticker != null || message != null) { runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, messageId, 0); } else { try { Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int userId = cursor.getInt(cursor.getColumnIndex("DATA4")); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); push_user_id = userId; } cursor.close(); } } catch (Exception e) { FileLog.e("tmessages", e); } } } } else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) { open_settings = 1; } else if (intent.getAction().startsWith("com.tmessages.openchat")) { int chatId = intent.getIntExtra("chatId", 0); int userId = intent.getIntExtra("userId", 0); int encId = intent.getIntExtra("encId", 0); if (chatId != 0) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_chat_id = chatId; } else if (userId != 0) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_user_id = userId; } else if (encId != 0) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_enc_id = encId; } else { showDialogsList = true; } } else if (intent.getAction().equals("com.tmessages.openplayer")) { showPlayer = true; } } } if (push_user_id != 0) { Bundle args = new Bundle(); args.putInt("user_id", push_user_id); if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); if (actionBarLayout.presentFragment(fragment, false, true, true)) { pushOpened = true; } } } else if (push_chat_id != 0) { Bundle args = new Bundle(); args.putInt("chat_id", push_chat_id); if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); if (actionBarLayout.presentFragment(fragment, false, true, true)) { pushOpened = true; } } } else if (push_enc_id != 0) { Bundle args = new Bundle(); args.putInt("enc_id", push_enc_id); ChatActivity fragment = new ChatActivity(args); if (actionBarLayout.presentFragment(fragment, false, true, true)) { pushOpened = true; } } else if (showDialogsList) { if (!AndroidUtilities.isTablet()) { actionBarLayout.removeAllFragments(); } else { if (!layersActionBarLayout.fragmentsStack.isEmpty()) { for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) { layersActionBarLayout .removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0)); a--; } layersActionBarLayout.closeLastFragment(false); } } pushOpened = false; isNew = false; } else if (showPlayer) { if (AndroidUtilities.isTablet()) { for (int a = 0; a < layersActionBarLayout.fragmentsStack.size(); a++) { BaseFragment fragment = layersActionBarLayout.fragmentsStack.get(a); if (fragment instanceof AudioPlayerActivity) { layersActionBarLayout.removeFragmentFromStack(fragment); break; } } actionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { for (int a = 0; a < actionBarLayout.fragmentsStack.size(); a++) { BaseFragment fragment = actionBarLayout.fragmentsStack.get(a); if (fragment instanceof AudioPlayerActivity) { actionBarLayout.removeFragmentFromStack(fragment); break; } } drawerLayoutContainer.setAllowOpenDrawer(true, false); } actionBarLayout.presentFragment(new AudioPlayerActivity(), false, true, true); pushOpened = true; } else if (videoPath != null || photoPathsArray != null || sendingText != null || documentsPathsArray != null || contactsToSend != null || documentsUrisArray != null) { if (!AndroidUtilities.isTablet()) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); } if (dialogId == 0) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); if (contactsToSend != null) { args.putString("selectAlertString", LocaleController.getString("SendContactTo", R.string.SendMessagesTo)); args.putString("selectAlertStringGroup", LocaleController.getString("SendContactToGroup", R.string.SendContactToGroup)); } else { args.putString("selectAlertString", LocaleController.getString("SendMessagesTo", R.string.SendMessagesTo)); args.putString("selectAlertStringGroup", LocaleController.getString("SendMessagesToGroup", R.string.SendMessagesToGroup)); } DialogsActivity fragment = new DialogsActivity(args); dialogsFragment = fragment; fragment.setDelegate(this); boolean removeLast; if (AndroidUtilities.isTablet()) { removeLast = layersActionBarLayout.fragmentsStack.size() > 0 && layersActionBarLayout.fragmentsStack.get( layersActionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity; } else { removeLast = actionBarLayout.fragmentsStack.size() > 1 && actionBarLayout.fragmentsStack .get(actionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity; } actionBarLayout.presentFragment(fragment, removeLast, true, true); pushOpened = true; if (PhotoViewer.getInstance().isVisible()) { PhotoViewer.getInstance().closePhoto(false, true); } drawerLayoutContainer.setAllowOpenDrawer(false, false); if (AndroidUtilities.isTablet()) { actionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); } else { drawerLayoutContainer.setAllowOpenDrawer(true, false); } } else { didSelectDialog(null, dialogId, false); } } else if (open_settings != 0) { actionBarLayout.presentFragment(new SettingsActivity(), false, true, true); if (AndroidUtilities.isTablet()) { actionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { drawerLayoutContainer.setAllowOpenDrawer(true, false); } pushOpened = true; } if (!pushOpened && !isNew) { if (AndroidUtilities.isTablet()) { if (!UserConfig.isClientActivated()) { if (layersActionBarLayout.fragmentsStack.isEmpty()) { layersActionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } } else { if (actionBarLayout.fragmentsStack.isEmpty()) { actionBarLayout.addFragmentToStack(new DialogsActivity(null)); drawerLayoutContainer.setAllowOpenDrawer(true, false); } } } else { if (actionBarLayout.fragmentsStack.isEmpty()) { if (!UserConfig.isClientActivated()) { actionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { actionBarLayout.addFragmentToStack(new DialogsActivity(null)); drawerLayoutContainer.setAllowOpenDrawer(true, false); } } } actionBarLayout.showLastFragment(); if (AndroidUtilities.isTablet()) { layersActionBarLayout.showLastFragment(); rightActionBarLayout.showLastFragment(); } } intent.setAction(null); return pushOpened; } return false; }
From source file:com.gelakinetic.mtgfam.FamiliarActivity.java
private boolean processIntent(Intent intent) { boolean isDeepLink = false; if (Intent.ACTION_SEARCH.equals(intent.getAction())) { /* Do a search by name, launched from the quick search */ String query = intent.getStringExtra(SearchManager.QUERY); Bundle args = new Bundle(); SearchCriteria sc = new SearchCriteria(); sc.name = query;//from w ww.j ava2 s . c om args.putSerializable(SearchViewFragment.CRITERIA, sc); selectItem(R.string.main_card_search, args, false, true); /* Don't clear backstack, do force the intent */ } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { boolean shouldSelectItem = true; Uri data = intent.getData(); Bundle args = new Bundle(); assert data != null; boolean shouldClearFragmentStack = true; /* Clear backstack for deep links */ if (data.getAuthority().toLowerCase().contains("gatherer.wizards")) { SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false); try { String queryParam; if ((queryParam = data.getQueryParameter("multiverseid")) != null) { Cursor cursor = CardDbAdapter.fetchCardByMultiverseId(Long.parseLong(queryParam), new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID }, database); if (cursor.getCount() != 0) { isDeepLink = true; args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) }); } cursor.close(); if (args.size() == 0) { throw new Exception("Not Found"); } } else if ((queryParam = data.getQueryParameter("name")) != null) { Cursor cursor = CardDbAdapter.fetchCardByName(queryParam, new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID }, true, database); if (cursor.getCount() != 0) { isDeepLink = true; args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) }); } cursor.close(); if (args.size() == 0) { throw new Exception("Not Found"); } } else { throw new Exception("Not Found"); } } catch (Exception e) { /* empty cursor, just return */ ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show(); this.finish(); shouldSelectItem = false; } finally { DatabaseManager.getInstance(this, false).closeDatabase(false); } } else if (data.getAuthority().contains("CardSearchProvider")) { /* User clicked a card in the quick search autocomplete, jump right to it */ args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { Long.parseLong(data.getLastPathSegment()) }); shouldClearFragmentStack = false; /* Don't clear backstack for search intents */ } else { /* User clicked a deep link, jump to the card(s) */ isDeepLink = true; SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false); try { Cursor cursor = null; boolean screenLaunched = false; if (data.getScheme().toLowerCase().equals("card") && data.getAuthority().toLowerCase().equals("multiverseid")) { if (data.getLastPathSegment() == null) { /* Home screen deep link */ launchHomeScreen(); screenLaunched = true; shouldSelectItem = false; } else { try { /* Don't clear the fragment stack for internal links (thanks Meld cards) */ if (data.getPathSegments().contains("internal")) { shouldClearFragmentStack = false; } cursor = CardDbAdapter.fetchCardByMultiverseId( Long.parseLong(data.getLastPathSegment()), new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID }, database); } catch (NumberFormatException e) { cursor = null; } } } if (cursor != null) { if (cursor.getCount() != 0) { args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) }); } else { /* empty cursor, just return */ ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show(); this.finish(); shouldSelectItem = false; } cursor.close(); } else if (!screenLaunched) { /* null cursor, just return */ ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show(); this.finish(); shouldSelectItem = false; } } catch (FamiliarDbException e) { e.printStackTrace(); } DatabaseManager.getInstance(this, false).closeDatabase(false); } args.putInt(CardViewPagerFragment.STARTING_CARD_POSITION, 0); if (shouldSelectItem) { selectItem(R.string.main_card_search, args, shouldClearFragmentStack, true); } } else if (ACTION_ROUND_TIMER.equals(intent.getAction())) { selectItem(R.string.main_timer, null, true, false); } else if (ACTION_CARD_SEARCH.equals(intent.getAction())) { selectItem(R.string.main_card_search, null, true, false); } else if (ACTION_LIFE.equals(intent.getAction())) { selectItem(R.string.main_life_counter, null, true, false); } else if (ACTION_DICE.equals(intent.getAction())) { selectItem(R.string.main_dice, null, true, false); } else if (ACTION_TRADE.equals(intent.getAction())) { selectItem(R.string.main_trade, null, true, false); } else if (ACTION_MANA.equals(intent.getAction())) { selectItem(R.string.main_mana_pool, null, true, false); } else if (ACTION_WISH.equals(intent.getAction())) { selectItem(R.string.main_wishlist, null, true, false); } else if (ACTION_RULES.equals(intent.getAction())) { selectItem(R.string.main_rules, null, true, false); } else if (ACTION_JUDGE.equals(intent.getAction())) { selectItem(R.string.main_judges_corner, null, true, false); } else if (ACTION_MOJHOSTO.equals(intent.getAction())) { selectItem(R.string.main_mojhosto, null, true, false); } else if (ACTION_PROFILE.equals(intent.getAction())) { selectItem(R.string.main_profile, null, true, false); } else if (ACTION_DECKLIST.equals(intent.getAction())) { selectItem(R.string.main_decklist, null, true, false); } else if (Intent.ACTION_MAIN.equals(intent.getAction())) { /* App launched as regular, show the default fragment if there isn't one already */ if (getSupportFragmentManager().getFragments() == null) { launchHomeScreen(); } } else { /* Some unknown intent, just finish */ finish(); } mDrawerList.setItemChecked(mCurrentFrag, true); return isDeepLink; }
From source file:com.bernard.beaconportal.activities.activity.MessageList.java
private boolean decodeExtras(Intent intent) { String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) { Uri uri = intent.getData(); List<String> segmentList = uri.getPathSegments(); String accountId = segmentList.get(0); Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts(); for (Account account : accounts) { if (String.valueOf(account.getAccountNumber()).equals(accountId)) { mMessageReference = new MessageReference(); mMessageReference.accountUuid = account.getUuid(); mMessageReference.folderName = segmentList.get(1); mMessageReference.uid = segmentList.get(2); break; }// www . j a v a 2s. co m } } else if (ACTION_SHORTCUT.equals(action)) { // Handle shortcut intents String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER); if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) { mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch(); } else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) { mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch(); } } else if (intent.getStringExtra(SearchManager.QUERY) != null) { // check if this intent comes from the system search ( remote ) if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // Query was received from Search Dialog String query = intent.getStringExtra(SearchManager.QUERY); mSearch = new LocalSearch(getString(R.string.search_results)); mSearch.setManualSearch(true); mNoThreading = true; mSearch.or(new SearchCondition(Searchfield.SENDER, Attribute.CONTAINS, query)); mSearch.or(new SearchCondition(Searchfield.SUBJECT, Attribute.CONTAINS, query)); mSearch.or(new SearchCondition(Searchfield.MESSAGE_CONTENTS, Attribute.CONTAINS, query)); Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT)); // searches started from a folder list activity will provide // an account, but no folder if (appData.getString(EXTRA_SEARCH_FOLDER) != null) { mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER)); } } else { mSearch.addAccountUuid(SearchSpecification.ALL_ACCOUNTS); } } } else { // regular LocalSearch object was passed mSearch = intent.getParcelableExtra(EXTRA_SEARCH); mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false); } if (mMessageReference == null) { mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); } if (mMessageReference != null) { mSearch = new LocalSearch(); mSearch.addAccountUuid(mMessageReference.accountUuid); mSearch.addAllowedFolder(mMessageReference.folderName); } if (mSearch == null) { // We've most likely been started by an old unread widget String accountUuid = intent.getStringExtra("account"); String folderName = intent.getStringExtra("folder"); mSearch = new LocalSearch(folderName); mSearch.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid); if (folderName != null) { mSearch.addAllowedFolder(folderName); } } Preferences prefs = Preferences.getPreferences(getApplicationContext()); String[] accountUuids = mSearch.getAccountUuids(); if (mSearch.searchAllAccounts()) { Account[] accounts = prefs.getAccounts(); mSingleAccountMode = (accounts.length == 1); if (mSingleAccountMode) { mAccount = accounts[0]; } } else { mSingleAccountMode = (accountUuids.length == 1); if (mSingleAccountMode) { mAccount = prefs.getAccount(accountUuids[0]); } } mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1); if (mSingleAccountMode && (mAccount == null || !mAccount.isAvailable(this))) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return false; } if (mSingleFolderMode) { mFolderName = mSearch.getFolderNames().get(0); } // now we know if we are in single account mode and need a subtitle mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE); return true; }
From source file:org.kontalk.ui.ComposeMessageFragment.java
private void processArguments(Bundle savedInstanceState) { Bundle args;/*from w ww. j ava2s.c o m*/ if (savedInstanceState != null) { Uri uri = savedInstanceState.getParcelable(Uri.class.getName()); // threadId = ContentUris.parseId(uri); args = new Bundle(); args.putString("action", ComposeMessage.ACTION_VIEW_USERID); args.putParcelable("data", uri); String currentPhoto = savedInstanceState.getString("currentPhoto"); if (currentPhoto != null) { mCurrentPhoto = new File(currentPhoto); } mAudioDialog = AudioDialog.onRestoreInstanceState(getActivity(), savedInstanceState, getAudioFragment(), this); if (mAudioDialog != null) { Log.d(TAG, "recreating audio dialog"); mAudioDialog.show(); } } else { args = myArguments(); } if (args != null && args.size() > 0) { final String action = args.getString("action"); // view intent if (Intent.ACTION_VIEW.equals(action)) { Uri uri = args.getParcelable("data"); ContentResolver cres = getActivity().getContentResolver(); /* * FIXME this will retrieve name directly from contacts, * resulting in a possible discrepancy with users database */ Cursor c = cres.query(uri, new String[] { Syncer.DATA_COLUMN_DISPLAY_NAME, Syncer.DATA_COLUMN_PHONE }, null, null, null); if (c.moveToFirst()) { mUserName = c.getString(0); mUserPhone = c.getString(1); // FIXME should it be retrieved from RawContacts.SYNC3 ?? mUserJID = XMPPUtils.createLocalJID(getActivity(), MessageUtils.sha1(mUserPhone)); Cursor cp = cres.query(Messages.CONTENT_URI, new String[] { Messages.THREAD_ID }, Messages.PEER + " = ?", new String[] { mUserJID }, null); if (cp.moveToFirst()) threadId = cp.getLong(0); cp.close(); } c.close(); if (threadId > 0) { mConversation = Conversation.loadFromId(getActivity(), threadId); } else { mConversation = Conversation.createNew(getActivity()); mConversation.setRecipient(mUserJID); } } // view conversation - just threadId provided else if (ComposeMessage.ACTION_VIEW_CONVERSATION.equals(action)) { Uri uri = args.getParcelable("data"); loadConversationMetadata(uri); } // view conversation - just userId provided else if (ComposeMessage.ACTION_VIEW_USERID.equals(action)) { Uri uri = args.getParcelable("data"); mUserJID = uri.getPathSegments().get(1); mConversation = Conversation.loadFromUserId(getActivity(), mUserJID); if (mConversation == null) { mConversation = Conversation.createNew(getActivity()); mConversation.setNumberHint(args.getString("number")); mConversation.setRecipient(mUserJID); } // this way avoid doing the users database query twice else { if (mConversation.getContact() == null) { mConversation.setNumberHint(args.getString("number")); mConversation.setRecipient(mUserJID); } } threadId = mConversation.getThreadId(); Contact contact = mConversation.getContact(); if (contact != null) { mUserName = contact.getName(); mUserPhone = contact.getNumber(); } else { mUserName = mUserJID; mUserPhone = null; } } } // set title if we are autonomous if (mArguments != null) { String title = mUserName; //if (mUserPhone != null) title += " <" + mUserPhone + ">"; setActivityTitle(title, ""); } // update conversation stuff if (mConversation != null) onConversationCreated(); // non existant thread - check for not synced contact if (threadId <= 0 && mConversation != null) { Contact contact = mConversation.getContact(); if (mUserPhone != null && contact != null ? !contact.isRegistered() : true) { // ask user to send invitation DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // FIXME is this specific to sms app? Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mUserPhone)); i.putExtra("sms_body", getString(R.string.text_invite_message)); startActivity(i); getActivity().finish(); } }; AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(getActivity()); builder.setTitle(R.string.title_user_not_found).setMessage(R.string.message_user_not_found) // nothing happens if user chooses to contact the user anyway .setPositiveButton(R.string.yes_user_not_found, null) .setNegativeButton(R.string.no_user_not_found, noListener).show(); } } }
From source file:com.tct.mail.compose.ComposeActivity.java
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null;/*from w w w .j a va 2 s .c o m*/ final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); String path = cursor.getString(index); //[BUGFIX]-Add by TCTNJ,chuang.wang, 2014-07-12,PR728605 Begin if (path != null && path.endsWith("RAW")) { //[BUGFIX]-Add by TCTNJ,chuang.wang, 2014-07-12,PR728605 END List<String> segments = uri.getPathSegments(); String dbName = segments.get(0); String id = segments.get(1); path = context.getDatabasePath(dbName + "_att") + "/" + id; } return path; } //[BUGFIX]-Mod-BEGIN by TSNJ,yong.tao,1/27/2015, PR-913357 } catch (Exception e) { //[BUGFIX]-Mod-END by TSNJ,yong.tao } finally { if (cursor != null) cursor.close(); } return null; }
From source file:com.tct.mail.compose.ComposeActivity.java
@SuppressLint("NewApi") public String getFilePath(Uri uri) { Uri thisUri = null; String path = ""; ContentResolver cr = this.getContentResolver(); if (uri == null) { return path; }//from www . j a v a 2 s . c om thisUri = uri; try { String scheme = thisUri.getScheme(); if (scheme == null) { path = thisUri.toString(); } else if (scheme.equals("file")) { path = thisUri.getPath(); path = changeDrmFileSuffix(path); } else if (DocumentsContract.isDocumentUri(this, uri)) { //ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris .withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(this, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } contentUri = contentUri.withAppendedPath(contentUri, split[1]); return getDataColumn(this, contentUri, null, null); } } else if (scheme.equals("content")) { String[] projection = { "_data" }; Cursor c = cr.query(thisUri, projection, null, null, null); if (c != null) { try { if (c.moveToFirst()) { path = c.getString(0); } } finally { c.close(); } } if (path.endsWith("RAW")) { List<String> segments = thisUri.getPathSegments(); String dbName = segments.get(0); String id = segments.get(1); path = this.getDatabasePath(dbName + "_att") + "/" + id; } } } catch (Exception e) { } return path; }