List of usage examples for android.content ContentResolver openInputStream
public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException
From source file:org.telegram.ui.LaunchActivity.java
private void handleIntent(Intent intent, boolean isNew, boolean restore) { boolean pushOpened = false; Integer push_user_id = 0;//from w w w.ja v a2s.c om Integer push_chat_id = 0; Integer push_enc_id = 0; Integer open_settings = 0; photoPath = null; videoPath = null; sendingText = null; documentPath = null; imagesPathArray = null; documentsPathArray = null; 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("text/plain")) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); 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 { error = true; } } else 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<String>(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(stream, "UTF-8")); String line = null; 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 = Utilities.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); } } } if (name != null && !phones.isEmpty()) { contactsToSend = new ArrayList<TLRPC.User>(); for (String phone : phones) { TLRPC.User user = new TLRPC.TL_userContact(); 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 { Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (parcelable == null) { return; } String path = null; if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } if (parcelable != null && type != null && type.startsWith("image/")) { photoPath = (Uri) parcelable; } else { path = Utilities.getPath((Uri) parcelable); if (path != null) { if (path.startsWith("file:")) { path = path.replace("file://", ""); } if (type != null && type.startsWith("video/")) { videoPath = path; } else { documentPath = path; } } else { 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) { if (type != null && type.startsWith("image/")) { Uri[] uris2 = new Uri[uris.size()]; for (int i = 0; i < uris2.length; i++) { Parcelable parcelable = uris.get(i); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } uris2[i] = (Uri) parcelable; } imagesPathArray = uris2; } else { String[] uris2 = new String[uris.size()]; for (int i = 0; i < uris2.length; i++) { Parcelable parcelable = uris.get(i); if (!(parcelable instanceof Uri)) { parcelable = Uri.parse(parcelable.toString()); } String path = Utilities.getPath((Uri) parcelable); if (path != null) { if (path.startsWith("file:")) { path = path.replace("file://", ""); } uris2[i] = path; } } documentsPathArray = uris2; } } 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())) { 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(MessagesController.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; } } if (getIntent().getAction() != null && getIntent().getAction().startsWith("com.tmessages.openchat") && (getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 && !restore) { int chatId = getIntent().getIntExtra("chatId", 0); int userId = getIntent().getIntExtra("userId", 0); int encId = getIntent().getIntExtra("encId", 0); if (chatId != 0) { TLRPC.Chat chat = MessagesController.getInstance().chats.get(chatId); if (chat != null) { NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); push_chat_id = chatId; } } else if (userId != 0) { TLRPC.User user = MessagesController.getInstance().users.get(userId); if (user != null) { NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); push_user_id = userId; } } else if (encId != 0) { TLRPC.EncryptedChat chat = MessagesController.getInstance().encryptedChats.get(encId); if (chat != null) { NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); push_enc_id = encId; } } } if (push_user_id != 0) { if (push_user_id == UserConfig.clientUserId) { open_settings = 1; } else { ChatActivity fragment = new ChatActivity(); Bundle bundle = new Bundle(); bundle.putInt("user_id", push_user_id); fragment.setArguments(bundle); if (fragment.onFragmentCreate()) { pushOpened = true; ApplicationLoader.fragmentsStack.add(fragment); getSupportFragmentManager().beginTransaction() .replace(R.id.container, fragment, "chat" + Math.random()).commitAllowingStateLoss(); } } } else if (push_chat_id != 0) { ChatActivity fragment = new ChatActivity(); Bundle bundle = new Bundle(); bundle.putInt("chat_id", push_chat_id); fragment.setArguments(bundle); if (fragment.onFragmentCreate()) { pushOpened = true; ApplicationLoader.fragmentsStack.add(fragment); getSupportFragmentManager().beginTransaction() .replace(R.id.container, fragment, "chat" + Math.random()).commitAllowingStateLoss(); } } else if (push_enc_id != 0) { ChatActivity fragment = new ChatActivity(); Bundle bundle = new Bundle(); bundle.putInt("enc_id", push_enc_id); fragment.setArguments(bundle); if (fragment.onFragmentCreate()) { pushOpened = true; ApplicationLoader.fragmentsStack.add(fragment); getSupportFragmentManager().beginTransaction() .replace(R.id.container, fragment, "chat" + Math.random()).commitAllowingStateLoss(); } } if (videoPath != null || photoPath != null || sendingText != null || documentPath != null || documentsPathArray != null || imagesPathArray != null || contactsToSend != null) { MessagesActivity fragment = new MessagesActivity(); fragment.selectAlertString = R.string.ForwardMessagesTo; fragment.selectAlertStringDesc = "ForwardMessagesTo"; fragment.animationType = 1; Bundle args = new Bundle(); args.putBoolean("onlySelect", true); fragment.setArguments(args); fragment.delegate = this; ApplicationLoader.fragmentsStack.add(fragment); fragment.onFragmentCreate(); getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, fragment.getTag()) .commitAllowingStateLoss(); pushOpened = true; } if (open_settings != 0) { SettingsActivity fragment = new SettingsActivity(); ApplicationLoader.fragmentsStack.add(fragment); fragment.onFragmentCreate(); getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, "settings") .commitAllowingStateLoss(); pushOpened = true; } if (!pushOpened && !isNew) { BaseFragment fragment = ApplicationLoader.fragmentsStack .get(ApplicationLoader.fragmentsStack.size() - 1); getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, fragment.getTag()) .commitAllowingStateLoss(); } getIntent().setAction(null); }
From source file:edu.mit.mobile.android.locast.net.NetworkClient.java
protected InputStream getFileStream(String localFilename) throws IOException { if (localFilename.startsWith("content:")) { final ContentResolver cr = this.mContext.getContentResolver(); return cr.openInputStream(Uri.parse(localFilename)); } else {//from w ww . j a va 2 s .c om return new FileInputStream(new File(localFilename)); } }
From source file:com.nnm.smsviet.Message.java
/** * Fetch MMS parts./* w w w. j av a 2 s . c o m*/ * * @param context * {@link Context} */ private void fetchMmsParts(final Context context) { final ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?", new String[] { String.valueOf(this.id) }, null); if (cursor == null || !cursor.moveToFirst()) { return; } final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]); final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]); final int iText = cursor.getColumnIndex("text"); do { final int pid = cursor.getInt(iID); final String ct = cursor.getString(iCT); Log.d(TAG, "part: " + pid + " " + ct); // get part InputStream is = null; final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid); try { is = cr.openInputStream(uri); } catch (IOException e) { Log.e(TAG, "Failed to load part data", e); } if (is == null) { Log.i(TAG, "InputStream for part " + pid + " is null"); if (iText >= 0 && ct.startsWith("text/")) { this.body = cursor.getString(iText); } continue; } if (ct == null) { continue; } if (ct.startsWith("image/")) { this.picture = BitmapFactory.decodeStream(is); final Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(uri, ct); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); this.contentIntent = i; continue; // skip the rest } else if (ct.startsWith("video/") || ct.startsWith("audio/")) { this.picture = BITMAP_PLAY; final Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(uri, ct); this.contentIntent = i; continue; // skip the rest } else if (ct.startsWith("text/")) { this.body = this.fetchPart(is); } if (is != null) { try { is.close(); } catch (IOException e) { Log.e(TAG, "Failed to close stream", e); } // Ignore } } while (cursor.moveToNext()); }
From source file:org.openintents.safe.CryptoHelper.java
/** * Dencrypt a file previously encrypted with * encryptFileWithSessionKey().//from w w w.j a va 2 s. c om * <p/> * The original file is not modified * * @param ctx Context of activity in order to store temp file * @param fileUri Uri to either a stream or a file to read from * @return If decryption is successful, returns Uri of a content * provider to read the plaintext file. Upon failure, * return null. * @throws Exception * @author Peli */ public Uri decryptFileWithSessionKeyThroughContentProvider(Context ctx, Uri fileUri) throws CryptoHelperException { if (debug) { Log.d(TAG, "fileUri=" + fileUri.toString()); } ContentResolver contentResolver = ctx.getContentResolver(); String sessionFile = ""; Uri resultUri = null; boolean result = false; try { InputStream is; if (fileUri.getScheme().equals("file")) { is = new java.io.FileInputStream(fileUri.getPath()); if (debug) { Log.d(TAG, "Decrypt: Input from " + fileUri.getPath()); } } else { is = contentResolver.openInputStream(fileUri); if (debug) { Log.d(TAG, "Decrypt: Input from " + fileUri.toString()); } } FileOutputStream os = null; String decryptSession; try { // create a random session name decryptSession = generateSalt(); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); String msg = "Decrypt error: " + e1.getLocalizedMessage(); throw new CryptoHelperException(msg); } sessionFile = CryptoContentProvider.SESSION_FILE + "." + decryptSession; if (debug) { Log.d(TAG, "Decrypt: Output to " + sessionFile); } // openFileOutput creates a file in /data/data/{packagename}/files/ // In our case, /data/data/org.openintents.safe/files/ // This file is owned and only readable by our application os = ctx.openFileOutput(sessionFile, Context.MODE_PRIVATE); // after writing the decrypted content to a temporary file, // pass back a Uri that can be used to read back the contents resultUri = Uri.withAppendedPath(CryptoContentProvider.CONTENT_URI, "decrypt/" + decryptSession); result = decryptStreamWithSessionKey(is, os); // Close the input stream is.close(); os.close(); } catch (FileNotFoundException e) { Log.e(TAG, "File not found", e); } catch (IOException e) { Log.e(TAG, "IOException", e); } if (result == false) { resultUri = null; // Unsuccessful. Clean up ctx.deleteFile(sessionFile); } return resultUri; }
From source file:com.google.android.apps.muzei.notifications.NewWallpaperNotificationReceiver.java
public static void maybeShowNewArtworkNotification(Context context) { ArtDetailOpenedClosedEvent adoce = EventBus.getDefault().getStickyEvent(ArtDetailOpenedClosedEvent.class); if (adoce != null && adoce.isArtDetailOpened()) { return;//from www . j a va 2s . c o m } if (!isNewWallpaperNotificationEnabled(context)) { return; } ContentResolver contentResolver = context.getContentResolver(); ArtworkSource artworkSource = MuzeiDatabase.getInstance(context).artworkDao() .getCurrentArtworkWithSourceBlocking(); if (artworkSource == null) { return; } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); long currentArtworkId = artworkSource.artwork.id; long lastReadArtworkId = sp.getLong(PREF_LAST_READ_NOTIFICATION_ARTWORK_ID, -1); String currentImageUri = artworkSource.artwork.imageUri != null ? artworkSource.artwork.imageUri.toString() : null; String lastReadImageUri = sp.getString(PREF_LAST_READ_NOTIFICATION_ARTWORK_IMAGE_URI, null); String currentToken = artworkSource.artwork.token; String lastReadToken = sp.getString(PREF_LAST_READ_NOTIFICATION_ARTWORK_TOKEN, null); // We've already dismissed the notification if the IDs match boolean previouslyDismissedNotification = lastReadArtworkId == currentArtworkId; // We've already dismissed the notification if the image URIs match and both are not empty previouslyDismissedNotification = previouslyDismissedNotification || (!TextUtils.isEmpty(lastReadImageUri) && !TextUtils.isEmpty(currentImageUri) && TextUtils.equals(lastReadImageUri, currentImageUri)); // We've already dismissed the notification if the tokens match and both are not empty previouslyDismissedNotification = previouslyDismissedNotification || (!TextUtils.isEmpty(lastReadToken) && !TextUtils.isEmpty(currentToken) && TextUtils.equals(lastReadToken, currentToken)); if (previouslyDismissedNotification) { return; } Bitmap largeIcon; Bitmap background; try { BitmapFactory.Options options = new BitmapFactory.Options(); // Check if there's rotation int rotation = 0; try (InputStream in = contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI)) { if (in == null) { return; } ExifInterface exifInterface = new ExifInterface(in); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } } catch (IOException | NumberFormatException | StackOverflowError e) { Log.w(TAG, "Couldn't open EXIF interface on artwork", e); } BitmapRegionLoader regionLoader = BitmapRegionLoader .newInstance(contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI), rotation); int width = regionLoader.getWidth(); int height = regionLoader.getHeight(); int shortestLength = Math.min(width, height); options.inJustDecodeBounds = false; int largeIconHeight = context.getResources() .getDimensionPixelSize(android.R.dimen.notification_large_icon_height); options.inSampleSize = ImageUtil.calculateSampleSize(shortestLength, largeIconHeight); largeIcon = regionLoader.decodeRegion(new Rect(0, 0, width, height), options); // Use the suggested 400x400 for Android Wear background images per // http://developer.android.com/training/wearables/notifications/creating.html#AddWearableFeatures options.inSampleSize = ImageUtil.calculateSampleSize(height, 400); background = regionLoader.decodeRegion(new Rect(0, 0, width, height), options); } catch (IOException e) { Log.e(TAG, "Unable to load artwork to show notification", e); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(context); } String artworkTitle = artworkSource.artwork.title; String title = TextUtils.isEmpty(artworkTitle) ? context.getString(R.string.app_name) : artworkTitle; NotificationCompat.Builder nb = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_muzei) .setColor(ContextCompat.getColor(context, R.color.notification)) .setPriority(NotificationCompat.PRIORITY_MIN).setAutoCancel(true).setContentTitle(title) .setContentText(context.getString(R.string.notification_new_wallpaper)).setLargeIcon(largeIcon) .setContentIntent(PendingIntent.getActivity(context, 0, context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()), PendingIntent.FLAG_UPDATE_CURRENT)) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class) .setAction(ACTION_MARK_NOTIFICATION_READ), PendingIntent.FLAG_UPDATE_CURRENT)); NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle().bigLargeIcon(null) .setBigContentTitle(title).setSummaryText(artworkSource.artwork.byline).bigPicture(background); nb.setStyle(style); NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender(); // Support Next Artwork if (artworkSource.supportsNextArtwork) { PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class).setAction(ACTION_NEXT_ARTWORK), PendingIntent.FLAG_UPDATE_CURRENT); nb.addAction(R.drawable.ic_notif_next_artwork, context.getString(R.string.action_next_artwork_condensed), nextPendingIntent); // Android Wear uses larger action icons so we build a // separate action extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_next_artwork, context.getString(R.string.action_next_artwork_condensed), nextPendingIntent) .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false)) .build()); } List<UserCommand> commands = artworkSource.commands; // Show custom actions as a selectable list on Android Wear devices if (!commands.isEmpty()) { String[] actions = new String[commands.size()]; for (int h = 0; h < commands.size(); h++) { actions[h] = commands.get(h).getTitle(); } PendingIntent userCommandPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class).setAction(ACTION_USER_COMMAND), PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_USER_COMMAND).setAllowFreeFormInput(false) .setLabel(context.getString(R.string.action_user_command_prompt)).setChoices(actions).build(); extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_user_command, context.getString(R.string.action_user_command), userCommandPendingIntent) .addRemoteInput(remoteInput) .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false)) .build()); } Intent viewIntent = artworkSource.artwork.viewIntent; if (viewIntent != null) { viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT); nb.addAction(R.drawable.ic_notif_info, context.getString(R.string.action_artwork_info), nextPendingIntent); // Android Wear uses larger action icons so we build a // separate action extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_info, context.getString(R.string.action_artwork_info), nextPendingIntent) .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false)) .build()); } catch (RuntimeException ignored) { // This is actually meant to catch a FileUriExposedException, but you can't // have catch statements for exceptions that don't exist at your minSdkVersion } } nb.extend(extender); // Hide the image and artwork title for the public version NotificationCompat.Builder publicBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.ic_stat_muzei) .setColor(ContextCompat.getColor(context, R.color.notification)) .setPriority(NotificationCompat.PRIORITY_MIN).setAutoCancel(true) .setContentTitle(context.getString(R.string.app_name)) .setContentText(context.getString(R.string.notification_new_wallpaper)) .setContentIntent(PendingIntent.getActivity(context, 0, context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()), PendingIntent.FLAG_UPDATE_CURRENT)) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, new Intent(context, NewWallpaperNotificationReceiver.class) .setAction(ACTION_MARK_NOTIFICATION_READ), PendingIntent.FLAG_UPDATE_CURRENT)); nb.setPublicVersion(publicBuilder.build()); NotificationManagerCompat nm = NotificationManagerCompat.from(context); nm.notify(NOTIFICATION_ID, nb.build()); }
From source file:com.vuze.android.remote.SessionInfo.java
private void openTorrent_perms(Activity activity, Uri uri) { try {//www .j av a 2 s.c om InputStream stream = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { String realPath = PaulBurkeFileUtils.getPath(activity, uri); if (realPath != null) { String meh = realPath.startsWith("/") ? "file://" + realPath : realPath; stream = activity.getContentResolver().openInputStream(Uri.parse(meh)); } } if (stream == null) { ContentResolver contentResolver = activity.getContentResolver(); stream = contentResolver.openInputStream(uri); } openTorrent(activity, uri.toString(), stream); } catch (SecurityException e) { if (AndroidUtils.DEBUG) { e.printStackTrace(); } VuzeEasyTracker.getInstance(activity).logError(e); String s = "Security Exception trying to access <b>" + uri + "</b>"; Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { if (AndroidUtils.DEBUG) { e.printStackTrace(); } VuzeEasyTracker.getInstance(activity).logError(e); String s = "<b>" + uri + "</b> not found"; if (e.getCause() != null) { s += ". " + e.getCause().getMessage(); } Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show(); } }
From source file:me.myatminsoe.myansms.Message.java
/** * Fetch MMS parts.//ww w . j a v a 2 s . c o m * * @param context {@link Context} */ private void fetchMmsParts(final Context context) { final ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?", new String[] { String.valueOf(id) }, null); if (cursor == null || !cursor.moveToFirst()) { return; } final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]); final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]); final int iText = cursor.getColumnIndex("text"); do { final int pid = cursor.getInt(iID); final String ct = cursor.getString(iCT); // get part InputStream is = null; final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid); if (uri == null) { continue; } try { is = cr.openInputStream(uri); } catch (IOException | NullPointerException e) { } if (is == null) { if (iText >= 0 && ct != null && ct.startsWith("text/")) { body = cursor.getString(iText); } continue; } if (ct == null) { continue; } if (ct.startsWith("image/")) { picture = BitmapFactory.decodeStream(is); final Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(uri, ct); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); contentIntent = i; continue; // skip the rest } else if (ct.startsWith("video/") || ct.startsWith("audio/")) { picture = BITMAP_PLAY; final Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(uri, ct); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); contentIntent = i; continue; // skip the rest } else if (ct.startsWith("text/")) { body = fetchPart(is); } try { is.close(); } catch (IOException e) { } // Ignore } while (cursor.moveToNext()); }
From source file:org.openintents.safe.CryptoHelper.java
/** * encrypt a file using a random session key * * @param contentResolver is used to be able to read the stream * @param fileUri is the stream or file to read from * @return Uri to the created plaintext file * @throws Exception//from w ww . j ava2 s.com * @author Peli */ public Uri encryptFileWithSessionKey(ContentResolver contentResolver, Uri fileUri) throws CryptoHelperException { if (debug) { Log.d(TAG, "Encrypt with session key"); } status = false; // assume failure if (password == null) { String msg = "Must call setPassword before runing encrypt."; throw new CryptoHelperException(msg); } String outputPath = ""; try { InputStream is; if (fileUri.getScheme().equals("file")) { is = new java.io.FileInputStream(fileUri.getPath()); outputPath = fileUri.getPath() + OISAFE_EXTENSION; } else { is = contentResolver.openInputStream(fileUri); outputPath = getTemporaryFileName(); } FileOutputStream os = new FileOutputStream(outputPath); byte[] cipherSessionKey = {}; // byte[] ciphertext = {}; // First create a session key SecretKey sessionKey = null; byte[] sessionKeyEncoded = null; // String sessionKeyString = null; try { KeyGenerator keygen; keygen = KeyGenerator.getInstance("AES"); keygen.init(256); // needs 96 bytes //keygen.init(128); // needs 64 bytes sessionKey = keygen.generateKey(); sessionKeyEncoded = sessionKey.getEncoded(); // sessionKeyString = new String(sessionKeyEncoded); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "generateMasterKey(): " + e.toString()); return null; } // Encrypt the session key using the master key try { pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded); status = true; } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { Log.e(TAG, "encryptWithSessionKey(): " + e.toString()); } if (!status) { return null; } status = false; String stringCipherVersion = "A"; byte[] bytesCipherVersion = stringCipherVersion.getBytes(); os.write(bytesCipherVersion, 0, bytesCipherVersion.length); os.write(cipherSessionKey, 0, cipherSessionKey.length); if (debug) { Log.d(TAG, "bytesCipherVersion.length: " + bytesCipherVersion.length); } if (debug) { Log.d(TAG, "cipherSessionKey.length: " + cipherSessionKey.length); } Trivium tri = new Trivium(); try { tri.setupKey(Trivium.MODE_ENCRYPT, sessionKeyEncoded, 0); tri.setupNonce(sessionKeyEncoded, 10); // Create the byte array to hold the data final int bytesLen = 4096; // buffer length byte[] bytesIn = new byte[bytesLen]; byte[] bytesOut = new byte[bytesLen]; int offset = 0; int numRead = 0; while ((numRead = is.read(bytesIn, 0, bytesLen)) >= 0) { tri.process(bytesIn, 0, bytesOut, 0, numRead); os.write(bytesOut, 0, numRead); offset += numRead; } // Ensure all the bytes have been read in if (offset < is.available()) { throw new IOException("Could not completely read file "); } // Close the input stream and return bytes is.close(); os.close(); // Securely delete the original file: SecureDelete.delete(new File(fileUri.getPath())); status = true; } catch (ESJException e) { Log.e(TAG, "Error encrypting file", e); } } catch (FileNotFoundException e) { Log.e(TAG, "File not found", e); } catch (IOException e) { Log.e(TAG, "IO Exception", e); } if (status == false) { return null; } return Uri.fromFile(new File(outputPath)); //Uri.parse("file://" + outputPath); // TODO: UUEncode }
From source file:org.openintents.safe.CryptoHelper.java
/** * Dencrypt a file previously encrypted with * encryptFileWithSessionKey().// w w w . j a va 2s. c o m * <p/> * Creates a new file without the .oisafe extension. * * @param ctx Context of activity in order to store temp file * @param fileUri Uri to either a stream or a file to read from * @return If decryption is successful, returns Uri of a content * provider to read the plaintext file. Upon failure, * return null. * @throws Exception * @author Peli */ public Uri decryptFileWithSessionKey(Context ctx, Uri fileUri) throws CryptoHelperException { if (debug) { Log.d(TAG, "fileUri=" + fileUri.toString()); } ContentResolver contentResolver = ctx.getContentResolver(); String inputPath = null; String outputPath = null; Uri resultUri = null; boolean result = false; try { InputStream is; if (fileUri.getScheme().equals("file")) { inputPath = fileUri.getPath(); is = new java.io.FileInputStream(inputPath); if (debug) { Log.d(TAG, "Decrypt: Input from " + inputPath); } if (inputPath.endsWith(OISAFE_EXTENSION)) { outputPath = inputPath.substring(0, inputPath.length() - OISAFE_EXTENSION.length()); } } else { is = contentResolver.openInputStream(fileUri); if (debug) { Log.d(TAG, "Decrypt: Input from " + fileUri.toString()); } } if (outputPath == null) { outputPath = getTemporaryFileName(); } FileOutputStream os = new FileOutputStream(outputPath); // after writing the decrypted content to a temporary file, // pass back a Uri that can be used to read back the contents resultUri = Uri.fromFile(new File(outputPath)); //Uri.parse("file://" + outputPath); // TODO: UUEncode? result = decryptStreamWithSessionKey(is, os); // Close the input stream is.close(); os.close(); } catch (FileNotFoundException e) { Log.e(TAG, "File not found", e); } catch (IOException e) { Log.e(TAG, "IOException", e); } catch (IllegalArgumentException e) { Log.e(TAG, "IllegalArgumentException", e); } if (result == true) { // Successful // Securely delete the original file: if (inputPath != null) { SecureDelete.delete(new File(inputPath)); } } else { resultUri = null; // Unsuccessful. Clean up //ctx.deleteFile(sessionFile); } return resultUri; }
From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java
/** * Get a {@link InputStream} from {@link Uri}. * // w w w .ja v a 2s. co m * @param cr * {@link ContentResolver} * @param uri * {@link Uri} * @return {@link InputStream} */ private InputStream getStream(final ContentResolver cr, final Uri uri) { if (uri.toString().startsWith("import")) { String url; if (uri.getScheme().equals("imports")) { url = "https:/"; } else { url = "http:/"; } url += uri.getPath(); final HttpGet request = new HttpGet(url); Log.d(TAG, "url: " + url); try { final HttpResponse response = new DefaultHttpClient().execute(request); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpStatus.SC_OK) { return null; } return response.getEntity().getContent(); } catch (IOException e) { Log.e(TAG, "error in reading export: " + url, e); return null; } } else if (uri.toString().startsWith("content://") || uri.toString().startsWith("file://")) { try { return cr.openInputStream(uri); } catch (IOException e) { Log.e(TAG, "error in reading export: " + uri.toString(), e); return null; } } Log.d(TAG, "getStream() returns null, " + uri.toString()); return null; }