List of usage examples for android.support.v4.content FileProvider getUriForFile
public static Uri getUriForFile(Context context, String str, File file)
From source file:net.bluehack.ui.WallpapersActivity.java
@Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setTitle(LocaleController.getString("ChatBackground", R.string.ChatBackground)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override/* w w w. j a va2 s . c om*/ public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { boolean done; TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground); if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) { int width = AndroidUtilities.displaySize.x; int height = AndroidUtilities.displaySize.y; if (width > height) { int temp = width; width = height; height = temp; } TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes, Math.min(width, height)); String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg"; File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg"); try { done = AndroidUtilities.copyFile(f, toFile); } catch (Exception e) { done = false; FileLog.e("tmessages", e); } } else { if (selectedBackground == -1) { File fromFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper-temp.jpg"); File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg"); done = fromFile.renameTo(toFile); } else { done = true; } } if (done) { SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("selectedBackground", selectedBackground); editor.putInt("selectedColor", selectedColor); editor.commit(); ApplicationLoader.reloadWallpaper(); } finishFragment(); } } }); ActionBarMenu menu = actionBar.createMenu(); doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); FrameLayout frameLayout = new FrameLayout(context); fragmentView = frameLayout; backgroundImage = new ImageView(context); backgroundImage.setScaleType(ImageView.ScaleType.CENTER_CROP); frameLayout.addView(backgroundImage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); backgroundImage.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); progressView = new FrameLayout(context); progressView.setVisibility(View.INVISIBLE); frameLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 52)); progressViewBackground = new View(context); progressViewBackground.setBackgroundResource(R.drawable.system_loader); progressView.addView(progressViewBackground, LayoutHelper.createFrame(36, 36, Gravity.CENTER)); ProgressBar progressBar = new ProgressBar(context); try { progressBar.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.loading_animation)); } catch (Exception e) { //don't promt } progressBar.setIndeterminate(true); AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500); progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER)); RecyclerListView listView = new RecyclerListView(context); listView.setClipToPadding(false); listView.setTag(8); listView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0); LinearLayoutManager layoutManager = new LinearLayoutManager(context); layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); listView.setLayoutManager(layoutManager); listView.setDisallowInterceptTouchEvents(true); listView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); listView.setAdapter(listAdapter = new ListAdapter(context)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 102, Gravity.LEFT | Gravity.BOTTOM)); listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (position == 0) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("Cancel", R.string.Cancel) }; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { try { if (i == 0) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = AndroidUtilities.generatePicturePath(); if (image != null) { if (Build.VERSION.SDK_INT >= 24) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", image)); takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); } currentPicturePath = image.getAbsolutePath(); } startActivityForResult(takePictureIntent, 10); } else if (i == 1) { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, 11); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); showDialog(builder.create()); } else { if (position - 1 < 0 || position - 1 >= wallPapers.size()) { return; } TLRPC.WallPaper wallPaper = wallPapers.get(position - 1); selectedBackground = wallPaper.id; listAdapter.notifyDataSetChanged(); processSelectedBackground(); } } }); processSelectedBackground(); return fragmentView; }
From source file:ch.blinkenlights.android.vanilla.MediaUtils.java
/** * Creates and sends a share intent across the system. * @param ctx context to execute resolving on. * @param song the song to share.//from w w w . j av a 2 s. co m */ public static void shareMedia(Context ctx, Song song) { if (song == null || song.path == null) return; Uri uri = null; try { uri = FileProvider.getUriForFile(ctx, ctx.getApplicationContext().getPackageName() + ".fileprovider", new File(song.path)); } catch (IllegalArgumentException e) { Toast.makeText(ctx, R.string.share_failed, Toast.LENGTH_SHORT).show(); } if (uri == null) return; // Fileprovider failed, we can not continue. Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("audio/*"); intent.putExtra(Intent.EXTRA_STREAM, uri); try { ctx.startActivity(Intent.createChooser(intent, ctx.getString(R.string.sendto))); } catch (ActivityNotFoundException e) { Toast.makeText(ctx, R.string.no_receiving_apps, Toast.LENGTH_SHORT).show(); } }
From source file:com.android.mms.transaction.NotificationTransaction.java
public void sendNotifyRespInd(int status) { MmsLog.i(MmsApp.TXN_TAG, "NotificationTransaction: sendNotifyRespInd()"); // Create the M-NotifyResp.ind NotifyRespInd notifyRespInd = null;// w w w . ja v a2 s .co m try { notifyRespInd = new NotifyRespInd(PduHeaders.CURRENT_MMS_VERSION, mNotificationInd.getTransactionId(), status); } catch (InvalidHeaderValueException ex) { ex.printStackTrace(); return; } /// M:Code analyze 014, this paragraph below is using for judging if it is allowed /// to send delivery report,at present,we don't support delivery report in MMS @{ mOpNotificationTransactionExt.sendNotifyRespInd(mContext, mSubId, notifyRespInd); byte[] datas = new PduComposer(mContext, notifyRespInd).make(); File pduFile = createPduFile(datas, NOTIFY_RESP_NAME + mUri.getLastPathSegment()); if (pduFile == null) { return; } SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId); /* Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED); intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId); // intent.putExtra(TransactionBundle.URI, mUri.toString()); PendingIntent sentIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); */ // Pack M-NotifyResp.ind and send it Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, pduFile); if (MmsConfig.getNotifyWapMMSC()) { manager.sendMultimediaMessage(mContext, pduFileUri, mContentLocation, null, null); } else { manager.sendMultimediaMessage(mContext, pduFileUri, null, null, null); } }
From source file:kr.wdream.ui.WallpapersActivity.java
@Override public View createView(Context context) { Log.d(LOG_TAG, "createView"); actionBar.setBackButtonImage(kr.wdream.storyshop.R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setTitle(/*from w ww . j a v a2 s . c o m*/ LocaleController.getString("ChatBackground", kr.wdream.storyshop.R.string.ChatBackground)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { boolean done; TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground); if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) { int width = AndroidUtilities.displaySize.x; int height = AndroidUtilities.displaySize.y; if (width > height) { int temp = width; width = height; height = temp; } TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes, Math.min(width, height)); String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg"; File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg"); try { done = AndroidUtilities.copyFile(f, toFile); } catch (Exception e) { done = false; FileLog.e("tmessages", e); } } else { if (selectedBackground == -1) { File fromFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper-temp.jpg"); File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg"); done = fromFile.renameTo(toFile); } else { done = true; } } if (done) { SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("selectedBackground", selectedBackground); editor.putInt("selectedColor", selectedColor); editor.commit(); ApplicationLoader.reloadWallpaper(); } finishFragment(); } } }); ActionBarMenu menu = actionBar.createMenu(); doneButton = menu.addItemWithWidth(done_button, kr.wdream.storyshop.R.drawable.ic_done, AndroidUtilities.dp(56)); FrameLayout frameLayout = new FrameLayout(context); fragmentView = frameLayout; backgroundImage = new ImageView(context); backgroundImage.setScaleType(ImageView.ScaleType.CENTER_CROP); frameLayout.addView(backgroundImage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); backgroundImage.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); progressView = new FrameLayout(context); progressView.setVisibility(View.INVISIBLE); frameLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 52)); progressViewBackground = new View(context); progressViewBackground.setBackgroundResource(kr.wdream.storyshop.R.drawable.system_loader); progressView.addView(progressViewBackground, LayoutHelper.createFrame(36, 36, Gravity.CENTER)); ProgressBar progressBar = new ProgressBar(context); try { progressBar.setIndeterminateDrawable( context.getResources().getDrawable(kr.wdream.storyshop.R.drawable.loading_animation)); } catch (Exception e) { //don't promt } progressBar.setIndeterminate(true); AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500); progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER)); RecyclerListView listView = new RecyclerListView(context); listView.setClipToPadding(false); listView.setTag(8); listView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0); LinearLayoutManager layoutManager = new LinearLayoutManager(context); layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); listView.setLayoutManager(layoutManager); listView.setDisallowInterceptTouchEvents(true); listView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); listView.setAdapter(listAdapter = new ListAdapter(context)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 102, Gravity.LEFT | Gravity.BOTTOM)); listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (position == 0) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items = new CharSequence[] { LocaleController.getString("FromCamera", kr.wdream.storyshop.R.string.FromCamera), LocaleController.getString("FromGalley", kr.wdream.storyshop.R.string.FromGalley), LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel) }; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { try { if (i == 0) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = AndroidUtilities.generatePicturePath(); if (image != null) { if (Build.VERSION.SDK_INT >= 24) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", image)); takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); } currentPicturePath = image.getAbsolutePath(); } startActivityForResult(takePictureIntent, 10); } else if (i == 1) { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, 11); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); showDialog(builder.create()); } else { if (position - 1 < 0 || position - 1 >= wallPapers.size()) { return; } TLRPC.WallPaper wallPaper = wallPapers.get(position - 1); selectedBackground = wallPaper.id; listAdapter.notifyDataSetChanged(); processSelectedBackground(); } } }); processSelectedBackground(); return fragmentView; }
From source file:com.android.talkback.labeling.LabelManagerSummaryActivity.java
private void addExportCustomLabelClickListener() { final Button exportLabel = (Button) findViewById(R.id.export_labels); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { exportLabel.setVisibility(View.GONE); return;// w w w . j a va 2 s . c om } exportLabel.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { CustomLabelMigrationManager exporter = new CustomLabelMigrationManager(getApplicationContext()); exporter.exportLabels(new CustomLabelMigrationManager.SimpleLabelMigrationCallback() { @Override public void onLabelsExported(File file) { if (file == null) { notifyLabelExportFailure(); return; } Uri uri = FileProvider.getUriForFile(getApplicationContext(), FILE_AUTHORITY, file); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); shareIntent.setType("application/json"); String activityTitle = getResources().getString(R.string.label_choose_app_to_export); startActivity(Intent.createChooser(shareIntent, activityTitle)); } @Override public void onFail() { notifyLabelExportFailure(); } }); return; } }); }
From source file:com.hijacker.SendLogActivity.java
public void onUseEmail(View v) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/text"); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "kiriakopoulos44@gmail.com" }); intent.putExtra(Intent.EXTRA_SUBJECT, "Hijacker bug report"); Uri attachment = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", report); intent.putExtra(Intent.EXTRA_STREAM, attachment); intent.putExtra(Intent.EXTRA_TEXT, extraView.getText().toString()); startActivity(intent);/*from w ww . j a v a 2 s .co m*/ }
From source file:ru.dublgis.androidhelpers.DesktopUtils.java
public static boolean sendEmail(final Context ctx, final String to, final String subject, final String body, final String[] attachment, final String authorities) { try {//from w w w. j av a 2 s . c o m final String[] recipients = new String[] { to }; final Intent intent = new Intent( attachment.length > 1 ? Intent.ACTION_SEND_MULTIPLE : Intent.ACTION_SENDTO); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, recipients); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, body); boolean grant_permissions_workaround = false; final ArrayList<Uri> uri = new ArrayList<>(); if (attachment.length > 0) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { for (final String fileName : attachment) { uri.add(Uri.fromFile(new File(fileName))); } } else { // Android 6+: going the longer route. // For more information, please see: // http://stackoverflow.com/questions/32981194/android-6-cannot-share-files-anymore intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); grant_permissions_workaround = true; for (final String fileName : attachment) { uri.add(FileProvider.getUriForFile(ctx, authorities, new File(fileName))); } } // Should not put array with only one element into intent because of a bug in GMail. if (uri.size() == 1) { intent.putExtra(Intent.EXTRA_STREAM, uri.get(0)); } else { intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uri); } } final IntentResolverInfo mailtoIntentResolvers = new IntentResolverInfo(ctx.getPackageManager()); mailtoIntentResolvers .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", to, null))); final Intent chooserIntent; if (mailtoIntentResolvers.isEmpty()) { chooserIntent = Intent.createChooser(intent, null); } else { final IntentResolverInfo messageIntentResolvers = new IntentResolverInfo(ctx.getPackageManager()); messageIntentResolvers .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("sms", "", null))); messageIntentResolvers .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mms", "", null))); messageIntentResolvers .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("tel", "", null))); mailtoIntentResolvers.removeSamePackages(messageIntentResolvers.getResolveInfos()); final List<Intent> intentList = new ArrayList<>(); for (final ActivityInfo activityInfo : mailtoIntentResolvers.getResolveInfos()) { final String packageName = activityInfo.getPackageName(); final String name = activityInfo.getName(); // Some mail clients will not read the URI unless this is done. // See here: https://stackoverflow.com/questions/24467696/android-file-provider-permission-denial if (grant_permissions_workaround) { for (int i = 0; i < uri.size(); ++i) { try { ctx.grantUriPermission(packageName, uri.get(i), Intent.FLAG_GRANT_READ_URI_PERMISSION); } catch (final Throwable e) { Log.e(TAG, "grantUriPermission error: ", e); } } } final Intent cloneIntent = (Intent) intent.clone(); cloneIntent.setComponent(new ComponentName(packageName, name)); intentList.add(cloneIntent); } final Intent targetIntent = intentList.get(0); intentList.remove(0); chooserIntent = Intent.createChooser(targetIntent, null); if (!intentList.isEmpty()) { final Intent[] extraIntents = intentList.toArray(new Intent[intentList.size()]); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents); } else { chooserIntent.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, extraIntents); } } } chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ctx.startActivity(chooserIntent); return true; } catch (final Throwable exception) { Log.e(TAG, "sendEmail exception: ", exception); return false; } }
From source file:com.android.mms.transaction.RetrieveTransaction.java
private void sendNotifyRespInd(int status) { MmsLog.i(MmsApp.TXN_TAG, "RetrieveTransaction: sendNotifyRespInd()"); // Create the M-NotifyResp.ind try {// ww w .j a va2 s . c o m NotificationInd notificationInd = (NotificationInd) PduPersister.getPduPersister(mContext).load(mUri); NotifyRespInd notifyRespInd = null; try { notifyRespInd = new NotifyRespInd(PduHeaders.CURRENT_MMS_VERSION, notificationInd.getTransactionId(), status); } catch (InvalidHeaderValueException ex) { ex.printStackTrace(); return; } byte[] datas = new PduComposer(mContext, notifyRespInd).make(); File pduFile = createPduFile(datas, NOTIFY_RESP_NAME + mUri.getLastPathSegment()); if (pduFile == null) { return; } SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId); /* Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED); intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId); // intent.putExtra(TransactionBundle.URI, mUri.toString()); PendingIntent sentIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); */ // Pack M-NotifyResp.ind and send it Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, pduFile); if (MmsConfig.getNotifyWapMMSC()) { manager.sendMultimediaMessage(mContext, pduFileUri, mContentLocation, null, null); } else { manager.sendMultimediaMessage(mContext, pduFileUri, null, null, null); } } catch (Throwable t) { Log.e(TAG, Log.getStackTraceString(t)); } }
From source file:com.example.zayankovsky.homework.ui.ImageDetailActivity.java
private Uri getUriForImage() { BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable(); if (drawable == null) { return null; }/* ww w.j a v a 2s. com*/ // Get the files/images subdirectory of internal storage File imagesDir = new File(getFilesDir(), "images"); if (!imagesDir.mkdirs() && !imagesDir.isDirectory()) { return null; } File imageFile = new File(imagesDir, ImageWorker.getTitle() + ".png"); OutputStream outputStream = null; try { try { outputStream = new FileOutputStream(imageFile); drawable.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, outputStream); } finally { if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return null; } // Use the FileProvider to get a content URI try { return FileProvider.getUriForFile(this, "com.example.zayankovsky.homework.fileprovider", imageFile); } catch (IllegalArgumentException e) { return null; } }
From source file:de.tap.easy_xkcd.fragments.comics.FavoritesFragment.java
private void exportFavorites() { //Export the full favorites list as text StringBuilder sb = new StringBuilder(); String newline = System.getProperty("line.separator"); for (int i = 0; i < favorites.length; i++) { sb.append(favorites[i]).append(" - "); sb.append(prefHelper.getTitle(favorites[i])); sb.append(newline);//from w ww. ja v a2s. c o m } try { File sdCard = prefHelper.getOfflinePath(); File dir = new File(sdCard.getAbsolutePath() + "/easy xkcd"); File file = new File(dir, "favorites.txt"); FileWriter writer = new FileWriter(file); writer.append(sb.toString()); writer.flush(); writer.close(); //Provide option to send to any app that accepts text/plain content Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); Uri uri = FileProvider.getUriForFile(getActivity(), "de.tap.easy_xkcd.fileProvider", file); sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); sendIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.pref_export))); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getActivity(), "Export failed", Toast.LENGTH_SHORT).show(); } }