Java Code Examples for androidx.core.content.FileProvider#getUriForFile()

The following examples show how to use androidx.core.content.FileProvider#getUriForFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtil.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void dispatchTakePictureIntent(Fragment pF) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(pF.getActivity().getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile(pF);
            mFilePath = photoFile.getAbsolutePath();
        } catch (IOException ex) {
            // Error occurred while creating the File
            return;
        }
        // Continue only if the File was successfully created
        Uri photoURI = FileProvider.getUriForFile(pF.getActivity(),
            BuildConfig.APPLICATION_ID + ".provider",
            photoFile);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        pF.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
    }
}
 
Example 2
Source File: MaintenancePlugin.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sendLogs() {
    String recipient = SP.getString(R.string.key_maintenance_logs_email, "[email protected]");
    int amount = SP.getInt(R.string.key_maintenance_logs_amount, 2);

    String logDirectory = LoggerUtils.getLogDirectory();
    List<File> logs = this.getLogfiles(logDirectory, amount);

    File zipDir = this.ctx.getExternalFilesDir("exports");
    File zipFile = new File(zipDir, this.constructName());

    LOG.debug("zipFile: {}", zipFile.getAbsolutePath());
    File zip = this.zipLogs(zipFile, logs);

    Uri attachementUri = FileProvider.getUriForFile(this.ctx, BuildConfig.APPLICATION_ID + ".fileprovider", zip);
    Intent emailIntent = this.sendMail(attachementUri, recipient, "Log Export");
    LOG.debug("sending emailIntent");
    ctx.startActivity(emailIntent);
}
 
Example 3
Source File: IntentUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取安装 APP( 支持 8.0) 的意图
 * @param file      文件
 * @param isNewTask 是否开启新的任务栈
 * @return 安装 APP( 支持 8.0) 的意图
 */
public static Intent getInstallAppIntent(final File file, final boolean isNewTask) {
    if (file == null) return null;
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            data = Uri.fromFile(file);
        } else {
            data = FileProvider.getUriForFile(DevUtils.getContext(), DevUtils.getAuthority(), file);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        return getIntent(intent, isNewTask);
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getInstallAppIntent");
    }
    return null;
}
 
Example 4
Source File: DownloadService.java    From CrazyDaily with Apache License 2.0 6 votes vote down vote up
@Override
public void onSuccess(int taskId, File saveFile) {
    Toast.makeText(this, "下载完成,保存路径:" + saveFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(this, getString(R.string.file_provider_authorities), saveFile);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        uri = Uri.fromFile(saveFile);
    }
    intent.setData(uri);
    PendingIntent pendingintent = PendingIntent.getActivity(this, 0, intent, PendingIntent
            .FLAG_UPDATE_CURRENT);
    mTaskIds.get(taskId).builder.setContentIntent(pendingintent);
}
 
Example 5
Source File: AppUtil.java    From Aria with Apache License 2.0 6 votes vote down vote up
/**
 * 调用系统文件管理器选择文件
 *
 * @param file 不能是文件夹
 * @param mineType android 可用的minetype
 * @param requestCode 请求码
 */
public static void chooseFile(Activity activity, File file, String mineType, int requestCode) {
  if (file.isDirectory()) {
    ALog.e(TAG, "不能选择文件夹");
    return;
  }
  Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
  Uri uri;
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    uri = FileProvider.getUriForFile(activity.getApplicationContext(),
        BuildConfig.APPLICATION_ID + ".provider",
        file);
  } else {
    uri = Uri.fromFile(file);
  }

  intent.setDataAndType(uri, TextUtils.isEmpty(mineType) ? "*/*" : mineType);
  intent.addCategory(Intent.CATEGORY_OPENABLE);
  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

  activity.startActivityForResult(intent, requestCode);
}
 
Example 6
Source File: CameraActivity.java    From AndroidAnimationExercise with Apache License 2.0 6 votes vote down vote up
/**
 * 裁剪照片
 *
 * @param imageUrl
 */
private void CropTheImage(Uri imageUrl) {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(imageUrl, "image/*");
    cropIntent.putExtra("cropWidth", "true");
    cropIntent.putExtra("outputX", cropTargetWidth);
    cropIntent.putExtra("outputY", cropTargetHeight);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
        File file = new File(mContext.getCacheDir(), "test1.jpg");
        copyUrl = Uri.fromFile(file);
        Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
        cropIntent.putExtra("output", contentUri);
    } else {
        File copyFile = FileHelper.createFileByType(mContext, destType, String.valueOf(System.currentTimeMillis()));
        copyUrl = Uri.fromFile(copyFile);
        cropIntent.putExtra("output", copyUrl);
    }
    startActivityForResult(cropIntent, REQUEST_CODE_CROP_PIC);
}
 
Example 7
Source File: CreatePDF.java    From NClientV2 with Apache License 2.0 6 votes vote down vote up
private void createIntentOpen(File finalPath) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    Uri apkURI = FileProvider.getUriForFile(
            getApplicationContext(),getApplicationContext().getPackageName() + ".provider", finalPath);
    i.setDataAndType(apkURI, "application/pdf");
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    List<ResolveInfo> resInfoList = getApplicationContext().getPackageManager().queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        getApplicationContext().grantUriPermission(packageName, apkURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    notification.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0,i,0));
    LogUtility.d(apkURI.toString());

}
 
Example 8
Source File: DownloadBroadcastReceiver.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
private void displaySnackbar(final Context context, long completedDownloadReference, DownloadManager downloadManager) {
    if (!isFocusDownload(completedDownloadReference)) {
        return;
    }

    final DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(completedDownloadReference);
    try (Cursor cursor = downloadManager.query(query)) {
        if (cursor.moveToFirst()) {
            int statusColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(statusColumnIndex)) {
                String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                final String localUri = uriString.startsWith(FILE_SCHEME) ? uriString.substring(FILE_SCHEME.length()) : uriString;
                final String decoded = Uri.decode(localUri);
                File file = new File(decoded);
                final String mimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
                String fileName = DownloadUtils.guessFileName(null, null, decoded, null);
                final String fileName2 = DownloadUtils.guessFileName(null, null, decoded, mimeType);
                // Rename the file extension if it lacks a known MIME type and the server provided a Content-Type header.
                if (!fileName.equals(fileName2)) {
                    final File file2 = new File(file.getParent(), fileName2);
                    if (file.renameTo(file2)) {
                        file = file2;
                        fileName = fileName2;
                    }
                }

                final Uri uriForFile = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + FILE_PROVIDER_EXTENSION, file);
                final Intent openFileIntent = IntentUtils.INSTANCE.createOpenFileIntent(uriForFile, mimeType);
                showSnackbarForFilename(openFileIntent, context, fileName);
            }
        }
    }
    removeFromHashSet(completedDownloadReference);
}
 
Example 9
Source File: DynamicFileUtils.java    From dynamic-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Returns uri from the file. 
 * <p>It will automatically use the @link FileProvider} on API 24 and above devices.
 *
 * @param context The context to get the file provider.
 * @param file The file to get the uri.
 *
 * @return The uri from the file.
 *
 * @see Uri
 */
public static @Nullable Uri getUriFromFile(@NonNull Context context, @Nullable File file) {
    if (file == null) {
        return null;
    }

    if (DynamicSdkUtils.is23()) {
        return FileProvider.getUriForFile(context.getApplicationContext(),
                context.getPackageName() + FILE_PROVIDER, file);
    } else {
        return (Uri.fromFile(file));
    }
}
 
Example 10
Source File: UriUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 FileProvider File Path Uri
 * @param file      文件
 * @param authority android:authorities
 * @return 指定文件 {@link Uri}
 */
public static Uri getUriForFile(final File file, final String authority) {
    if (file == null || authority == null) return null;
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(DevUtils.getContext(), authority, file);
        } else {
            return Uri.fromFile(file);
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getUriForFile");
        return null;
    }
}
 
Example 11
Source File: ShareUtils.java    From CloudReader with Apache License 2.0 5 votes vote down vote up
public static Uri getUriWithPath(Context context, String filepath, String authority) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        //7.0以上的读取文件uri要用这种方式了 注意在manifests里注册
        return FileProvider.getUriForFile(context.getApplicationContext(), authority+ ".fileprovider", new File(filepath));
    } else {
        return Uri.fromFile(new File(filepath));
    }
}
 
Example 12
Source File: UriFileUtil.java    From MissZzzReader with Apache License 2.0 5 votes vote down vote up
/**
 * 获取URI
 * @param context
 * @param file
 * @return
 */
public static Uri getUriForFile(Context context, File file) {
    if (context == null || file == null) {
        throw new NullPointerException();
    }
    Uri uri;
    if (Build.VERSION.SDK_INT >= 24) {
        uri = FileProvider.getUriForFile(context.getApplicationContext(), context.getString(R.string.sys_file_provider), file);
    } else {
        uri = Uri.fromFile(file);
    }
    return uri;
}
 
Example 13
Source File: AndroidUtils.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 获取安装应用的Intent
 */
public static Intent getInstallIntent(Context context, File file) {
  Intent intent = new Intent();
  intent.setAction(Intent.ACTION_VIEW);
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri contentUri =
        FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", file);
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
  } else {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
  }
  return intent;
}
 
Example 14
Source File: HtmlHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static void embedInlineImages(Context context, long id, Document document, boolean local) throws IOException {
    DB db = DB.getInstance(context);
    for (Element img : document.select("img")) {
        String src = img.attr("src");
        if (src.startsWith("cid:")) {
            String cid = '<' + src.substring(4) + '>';
            EntityAttachment attachment = db.attachment().getAttachment(id, cid);
            if (attachment != null && attachment.available) {
                File file = attachment.getFile(context);
                if (local) {
                    Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);
                    img.attr("src", uri.toString());
                    Log.i("Inline image uri=" + uri);
                } else {
                    try (InputStream is = new FileInputStream(file)) {
                        byte[] bytes = new byte[(int) file.length()];
                        if (is.read(bytes) != bytes.length)
                            throw new IOException("length");

                        StringBuilder sb = new StringBuilder();
                        sb.append("data:");
                        sb.append(attachment.type);
                        sb.append(";base64,");
                        sb.append(Base64.encodeToString(bytes, Base64.NO_WRAP));

                        img.attr("src", sb.toString());
                    }
                }
            }
        }
    }
}
 
Example 15
Source File: Utils.java    From SmartPack-Kernel-Manager with GNU General Public License v3.0 5 votes vote down vote up
public static void shareItem(Context context, String name, String path, String string) {
    Uri uriFile = FileProvider.getUriForFile(context,
            BuildConfig.APPLICATION_ID + ".provider", new File(path));
    Intent shareScript = new Intent(Intent.ACTION_SEND);
    shareScript.setType("*/*");
    shareScript.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.share_by, name));
    shareScript.putExtra(Intent.EXTRA_TEXT, string);
    shareScript.putExtra(Intent.EXTRA_STREAM, uriFile);
    shareScript.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(Intent.createChooser(shareScript, context.getString(R.string.share_with)));
}
 
Example 16
Source File: MediaStoreCompat.java    From Matisse with Apache License 2.0 5 votes vote down vote up
public void dispatchCaptureIntent(Context context, int requestCode) {
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (photoFile != null) {
            mCurrentPhotoPath = photoFile.getAbsolutePath();
            mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(),
                    mCaptureStrategy.authority, photoFile);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
            captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                List<ResolveInfo> resInfoList = context.getPackageManager()
                        .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, mCurrentPhotoUri,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
            if (mFragment != null) {
                mFragment.get().startActivityForResult(captureIntent, requestCode);
            } else {
                mContext.get().startActivityForResult(captureIntent, requestCode);
            }
        }
    }
}
 
Example 17
Source File: LogsFragment.java    From EdXposedManager with GNU General Public License v3.0 5 votes vote down vote up
private void send() {
    Uri uri = FileProvider.getUriForFile(requireActivity(), BuildConfig.APPLICATION_ID + ".fileprovider", new File(LOG_PATH + activatedConfig.get("fileName") + LOG_SUFFIX));
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
    sendIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    sendIntent.setType("application/html");
    startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.menuSend)));
}
 
Example 18
Source File: IntentUtils.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Intent buildIntent(Context context, File file, String mime) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".flutter_downloader.provider", file);
        intent.setDataAndType(uri, mime);
    } else {
        intent.setDataAndType(Uri.fromFile(file), mime);
    }
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    return intent;
}
 
Example 19
Source File: MainActivity.java    From storage-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Save our Launcher image to the cache and return it as a content URI.
 *
 * IMPORTANT: This could trigger StrictMode. Do not do this in your app.
 * For the simplicity of the code sample, this is running on the Main thread
 * but these tasks should be done in a background thread.
 *
 * @throws IOException if image couldn't be saved to the cache.
 * @return image content Uri
 */
private Uri saveImageThumbnail() throws IOException {
    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    File cachePath = new File(getCacheDir(), IMAGE_CACHE_DIR);
    cachePath.mkdirs();
    FileOutputStream stream = new FileOutputStream(cachePath + "/" + IMAGE_FILE);
    bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
    stream.close();
    File imagePath = new File(getCacheDir(), IMAGE_CACHE_DIR);
    File newFile = new File(imagePath, IMAGE_FILE);
    return FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, newFile);
}
 
Example 20
Source File: ImagePicker.java    From ImagePicker with MIT License 5 votes vote down vote up
private Uri getCaptureImageOutputUri() {
    Uri outputFileUri = null;
    File getImage = activity != null ? activity.getExternalFilesDir("") : fragment.getActivity().getExternalFilesDir("");
    if (getImage != null) {
        //outputFileUri = Uri.fromFile(new File(getImage.getPath(), "profile.png"));
        String fileName = "IMG_" + System.currentTimeMillis() + ".png";
        filePath = new File(getImage.getPath(), fileName).getPath();
        outputFileUri = FileProvider.getUriForFile(activity != null ? activity : fragment.getActivity(),
                activity != null ? activity.getApplicationContext().getPackageName() + ".provider" : fragment.getActivity().getApplicationContext().getPackageName() + ".provider",
                new File(getImage.getPath(), fileName));
    }
    return outputFileUri;
}