androidx.core.content.FileProvider Java Examples

The following examples show how to use androidx.core.content.FileProvider. 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: MainActivity.java    From PDFCreatorAndroid with MIT License 7 votes vote down vote up
@Override
protected void onNextClicked(File savedPDFFile) {
    Intent intentShareFile = new Intent(Intent.ACTION_SEND);

    Uri apkURI = FileProvider.getUriForFile(
            getApplicationContext(),
            getApplicationContext()
                    .getPackageName() + ".provider", savedPDFFile);
    intentShareFile.setDataAndType(apkURI, URLConnection.guessContentTypeFromName(savedPDFFile.getName()));
    intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    intentShareFile.putExtra(Intent.EXTRA_STREAM,
            Uri.parse("file://" + savedPDFFile.getAbsolutePath()));

    startActivity(Intent.createChooser(intentShareFile, "Share File"));
}
 
Example #2
Source File: SocialSharePlugin.java    From social_share_plugin with BSD 2-Clause "Simplified" License 7 votes vote down vote up
private void instagramShare(String type, String imagePath) {
    final File image = new File(imagePath);
    final Uri uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".social.share.fileprovider",
            image);
    final Intent share = new Intent(Intent.ACTION_SEND);
    share.setType(type);
    share.putExtra(Intent.EXTRA_STREAM, uri);
    share.setPackage(INSTAGRAM_PACKAGE_NAME);
    share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    final Intent chooser = Intent.createChooser(share, "Share to");
    final List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(chooser,
            PackageManager.MATCH_DEFAULT_ONLY);

    for (ResolveInfo resolveInfo : resInfoList) {
        final String packageName = resolveInfo.activityInfo.packageName;
        activity.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    activity.startActivityForResult(chooser, INSTAGRAM_REQUEST_CODE);
}
 
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: MainActivity.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Send Logcat output via email
 */
private void sendLogcat() {
    final File cacheDir = getExternalCacheDir();
    if (cacheDir == null) {
        Log.i(TAG, "Unable to save Logcat. Shared storage is unavailable!");
        return;
    }
    final File file = new File(cacheDir, "idledaddy-logcat.txt");
    try {
        Utils.saveLogcat(file);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("*/*");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Idle Daddy Logcat");
    intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,
            getApplicationContext().getPackageName() + ".provider", file));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);
}
 
Example #5
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 #6
Source File: PictureUtils.java    From science-journal with Apache License 2.0 6 votes vote down vote up
public static void launchExternalEditor(
    Activity activity, AppAccount appAccount, String experimentId, String relativeFilePath) {
  File file =
      FileMetadataUtil.getInstance()
          .getExperimentFile(appAccount, experimentId, relativeFilePath);
  String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());
  String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
  if (!TextUtils.isEmpty(type)) {
    Intent intent = new Intent(Intent.ACTION_EDIT);
    Uri photoUri = FileProvider.getUriForFile(activity, activity.getPackageName(), file);
    intent.setDataAndType(photoUri, type);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    try {
      activity.startActivity(
          Intent.createChooser(
              intent, activity.getResources().getString(R.string.photo_editor_dialog_title)));
    } catch (ActivityNotFoundException e) {
      Log.e(TAG, "No activity found to handle this " + file.getAbsolutePath() + " type " + type);
    }
  } else {
    Log.w(TAG, "Could not find mime type for " + file.getAbsolutePath());
  }
}
 
Example #7
Source File: MainActivity.java    From lbry-android with MIT License 6 votes vote down vote up
public void requestVideoCapture() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        String outputPath = String.format("%s/record", Utils.getAppInternalStorageDir(this));
        File dir = new File(outputPath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }

        cameraOutputFilename = String.format("%s/VID_%s.mp4", outputPath, Helper.FILESTAMP_FORMAT.format(new Date()));
        Uri outputUri = FileProvider.getUriForFile(this, String.format("%s.fileprovider", getPackageName()), new File(cameraOutputFilename));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        startActivityForResult(intent, REQUEST_VIDEO_CAPTURE);
        return;
    }

    showError(getString(R.string.cannot_capture_video));
}
 
Example #8
Source File: MainActivity.java    From lbry-android with MIT License 6 votes vote down vote up
public void requestTakePhoto() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        String outputPath = String.format("%s/photos", Utils.getAppInternalStorageDir(this));
        File dir = new File(outputPath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }

        cameraOutputFilename = String.format("%s/IMG_%s.jpg", outputPath, Helper.FILESTAMP_FORMAT.format(new Date()));
        Uri outputUri = FileProvider.getUriForFile(this, String.format("%s.fileprovider", getPackageName()), new File(cameraOutputFilename));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
        return;
    }

    showError(getString(R.string.cannot_take_photo));
}
 
Example #9
Source File: ApkUtil.java    From AppUpdate with Apache License 2.0 6 votes vote down vote up
/**
 * 安装一个apk
 *
 * @param context     上下文
 * @param authorities Android N 授权
 * @param apk         安装包文件
 */
public static void installApk(Context context, String authorities, File apk) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(context, authorities, apk);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        uri = Uri.fromFile(apk);
    }
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    context.startActivity(intent);
}
 
Example #10
Source File: DCCTransferListAdapter.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
public void open() {
    if (mFileUri != null && mFileUri.length() > 0) {
        Uri uri = Uri.parse(mFileUri);
        if (uri.getScheme().equals("file"))
            uri = FileProvider.getUriForFile(itemView.getContext(),
                    "io.mrarm.irc.fileprovider", new File(uri.getPath()));
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, mimeType);
        try {
            itemView.getContext().startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(itemView.getContext(), R.string.dcc_error_no_activity,
                    Toast.LENGTH_SHORT).show();
        }
    } else {
        openMenu();
    }
}
 
Example #11
Source File: NotificationUtil.java    From AppUpdate with Apache License 2.0 6 votes vote down vote up
/**
 * 显示下载完成的通知,点击进行安装
 *
 * @param context     上下文
 * @param icon        图标
 * @param title       标题
 * @param content     内容
 * @param authorities Android N 授权
 * @param apk         安装包
 */
public static void showDoneNotification(Context context, int icon, String title, String content,
                                        String authorities, File apk) {
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    //不知道为什么需要先取消之前的进度通知,才能显示完成的通知。
    manager.cancel(requireManagerNotNull().getNotifyId());
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        uri = FileProvider.getUriForFile(context, authorities, apk);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        uri = Uri.fromFile(apk);
    }
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder builder = builderNotification(context, icon, title, content)
            .setContentIntent(pi);
    Notification notification = builder.build();
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    manager.notify(requireManagerNotNull().getNotifyId(), notification);
}
 
Example #12
Source File: NodeInflater.java    From financisto with GNU General Public License v2.0 6 votes vote down vote up
public PictureBuilder withPicture(final Context context, String pictureFileName) {
    final ImageView imageView = v.findViewById(R.id.picture);
    imageView.setOnClickListener(arg0 -> {
        if (isRequestingPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            return;
        }
        String fileName = (String) imageView.getTag(R.id.attached_picture);
        if (fileName != null) {
            Uri target = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, PicturesUtil.pictureFile(fileName, true));
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(target, "image/jpeg");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
        }
    });
    PicturesUtil.showImage(context, imageView, pictureFileName);
    return this;
}
 
Example #13
Source File: FastFileUtil.java    From UIWidget with Apache License 2.0 6 votes vote down vote up
/**
 * 安装App 使用lib FileProvider
 *
 * @param apkPath apk 文件对象
 */
public static void installApk(File apkPath, @NonNull String authority) {
    Context context = App.sContext;
    if (context == null || apkPath == null) {
        return;
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    // context 使用startActivity需增加 FLAG_ACTIVITY_NEW_TASK TAG 否则低版本上(目前发现在7.0以下版本)会提示以下错误
    //android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Uri apkUri;
    //判断版本是否在7.0以上
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        //加入provider
        apkUri = FileProvider.getUriForFile(context, authority, apkPath);
        //授予一个URI的临时权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        apkUri = Uri.fromFile(apkPath);
    }
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    context.startActivity(intent);
}
 
Example #14
Source File: Web3WebviewModule.java    From react-native-web3-webview with MIT License 6 votes vote down vote up
private Uri getOutputUri(String intentType) {
    File capturedFile = null;
    try {
        capturedFile = getCapturedFile(intentType);
    } catch (IOException e) {
        Log.e("CREATE FILE", "Error occurred while creating the File", e);
        e.printStackTrace();
    }

    // for versions below 6.0 (23) we use the old File creation & permissions model
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return Uri.fromFile(capturedFile);
    }

    // for versions 6.0+ (23) we use the FileProvider to avoid runtime permissions
    String packageName = getReactApplicationContext().getPackageName();
    return FileProvider.getUriForFile(getReactApplicationContext(), packageName + ".fileprovider", capturedFile);
}
 
Example #15
Source File: FastFileUtil.java    From FastLib with Apache License 2.0 6 votes vote down vote up
/**
 * 安装App 使用lib FileProvider
 * 使用{@link #getCacheDir()} ()}创建文件包
 *
 * @param apkPath apk 文件对象
 */
public static void installApk(File apkPath, @NonNull String authority) {
    Context context = FastManager.getInstance().getApplication().getApplicationContext();
    if (context == null || apkPath == null) {
        return;
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    // context 使用startActivity需增加 FLAG_ACTIVITY_NEW_TASK TAG 否则低版本上(目前发现在7.0以下版本)会提示以下错误
    //android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Uri apkUri;
    //判断版本是否在7.0以上
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        //加入provider
        apkUri = FileProvider.getUriForFile(context, authority, apkPath);
        //授予一个URI的临时权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        apkUri = Uri.fromFile(apkPath);
    }
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    context.startActivity(intent);
}
 
Example #16
Source File: UpdateManager.java    From a with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 安装apk
 */
public void installApk(File apkFile) {
    if (!apkFile.exists()) {
        return;
    }
    Intent intent = new Intent();
    //执行动作
    intent.setAction(Intent.ACTION_VIEW);
    //判读版本是否在7.0以上
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    } else {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    }
    try {
        activity.startActivity(intent);
    } catch (Exception e) {
        Log.d("wwd", "Failed to launcher installing activity");
    }
}
 
Example #17
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 #18
Source File: LogsHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
public static boolean exportLogFiles(@NonNull Context context, @NonNull Intent intent) {
    try {
        File parent = new File(context.getCacheDir(), "logs");
        if (!parent.exists() && !parent.mkdir())
            return false;

        Process process = Runtime.getRuntime().exec("logcat -d");
        File file = new File(parent, "logs-" + System.currentTimeMillis() + ".txt");
        try (FileOutputStream out = new FileOutputStream(file, false)) {
            CommonUtils.copy(process.getInputStream(), out);
        } finally {
            process.destroy();
        }

        Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".logs", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        return true;
    } catch (IllegalArgumentException | IOException ex) {
        Log.e(TAG, "Failed exporting logs.", ex);
    }

    return false;
}
 
Example #19
Source File: PictureSelectUtils.java    From PictureSelector with Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个图片地址uri,用于保存拍照后的照片
 *
 * @param activity
 * @return 图片的uri
 */
public static Uri createImagePathUri(Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //适配 Android Q
        String displayName = String.valueOf(System.currentTimeMillis());
        ContentValues values = new ContentValues(2);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, displayName);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //SD 卡是否可用,可用则用 SD 卡,否则用内部存储
            takePictureUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            takePictureUri = activity.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
        }
    } else {
        String pathName = new StringBuffer().append(FileUtils.getExtPicturesPath()).append(File.separator)
                .append(System.currentTimeMillis()).append(".jpg").toString();
        takePictureFile = new File(pathName);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //解决Android 7.0 拍照出现FileUriExposedException的问题
            String authority = activity.getPackageName() + ".fileProvider";
            takePictureUri = FileProvider.getUriForFile(activity, authority, takePictureFile);
        } else {
            takePictureUri = Uri.fromFile(takePictureFile);
        }
    }
    return takePictureUri;
}
 
Example #20
Source File: SendSettingsReceiver.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // Ignore this broadcast if this is the paid version
    if(context.getPackageName().equals(BuildConfig.BASE_APPLICATION_ID)) {
        Intent sendSettingsIntent = new Intent(ACTION_SEND_SETTINGS);
        sendSettingsIntent.setPackage(BuildConfig.PAID_APPLICATION_ID);

        BackupUtils.backup(context, new IntentBackupAgent(sendSettingsIntent));

        // Get images
        for(String filename : U.getImageFilenames()) {
            File file = new File(context.getFilesDir() + "/tb_images", filename);
            if(file.exists() && U.isPlayStoreRelease(context, BuildConfig.PAID_APPLICATION_ID)) {
                Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
                context.grantUriPermission(BuildConfig.PAID_APPLICATION_ID, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                sendSettingsIntent.putExtra(filename, uri);
            }
        }

        // Finally, send the broadcast
        context.sendBroadcast(sendSettingsIntent);
    }
}
 
Example #21
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 #22
Source File: UpdateManager.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 安装apk
 */
public void installApk(File apkFile) {
    if (!apkFile.exists()) {
        return;
    }
    Intent intent = new Intent();
    //执行动作
    intent.setAction(Intent.ACTION_VIEW);
    //判读版本是否在7.0以上
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    } else {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    }
    try {
        activity.startActivity(intent);
    } catch (Exception e) {
        Log.d("wwd", "Failed to launcher installing activity");
    }
}
 
Example #23
Source File: FileProvider7.java    From WanAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 通过file获得content://
 */
public static Uri getUriForFile24(Context context, File file) {
    Uri fileUri = FileProvider.getUriForFile(
            context,
            context.getPackageName() + ".fileprovider",
            file);
    return fileUri;
}
 
Example #24
Source File: UIUtils.java    From rebootmenu with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 打开文件(字面意思)
 *
 * @param context  {@link Context}
 * @param filePath 文件完整路径
 * @return 是否成功打开
 */
public static boolean openFile(Context context, String filePath) {
    File f = new File(filePath);
    Uri uri = Build.VERSION.SDK_INT < Build.VERSION_CODES.N
            ? Uri.fromFile(f)
            : FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".file_provider", f);
    try {
        context.startActivity(new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION)
                .setDataAndType(uri, getMimeTypeFromUrl(filePath)));
        return true;
    } catch (ActivityNotFoundException ignored) {
        return false;
    }
}
 
Example #25
Source File: GameRoundDialog.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
private void share(@NonNull Context context) {
    File image = save(new File(context.getFilesDir(), "gameRoundImages"));
    if (image == null) {
        Toaster.with(context).message(R.string.failedSavingImage).show();
        return;
    }

    Uri uri = FileProvider.getUriForFile(context, "com.gianlu.pretendyourexyzzy", image);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setDataAndType(uri, "image/png");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(Intent.createChooser(intent, "Send to..."));
    dismissAllowingStateLoss();
}
 
Example #26
Source File: MainActivity.java    From Rucky with GNU General Public License v3.0 5 votes vote down vote up
void installUpdate() {
    notificationManager.cancel(2);
    File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"rucky.apk");
    Uri apkUri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        apkUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file);
    } else {
        apkUri = Uri.fromFile(file);
    }
    Intent installer = new Intent(Intent.ACTION_VIEW);
    installer.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    installer.setDataAndType(apkUri, "application/vnd.android.package-archive");
    installer.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(installer);
}
 
Example #27
Source File: BackupManager.java    From XposedSmsCode with GNU General Public License v3.0 5 votes vote down vote up
public static void shareBackupFile(Context context, File file) {
    Intent intent = new Intent(Intent.ACTION_SEND);

    Uri uri = FileProvider.getUriForFile(context, BACKUP_FILE_AUTHORITY, file);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setType(BACKUP_MIME_TYPE);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(Intent.createChooser(intent, null));
}
 
Example #28
Source File: CameraActivity.java    From AndroidProject with Apache License 2.0 5 votes vote down vote up
@Override
protected void initData() {
    // 启动系统相机
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (XXPermissions.isHasPermission(this, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA)
            && intent.resolveActivity(getPackageManager()) != null) {
        mFile = getSerializable(IntentKey.FILE);
        if (mFile != null && mFile.exists()) {

            Uri imageUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 通过 FileProvider 创建一个 Content 类型的 Uri 文件
                imageUri = FileProvider.getUriForFile(this, AppConfig.getPackageName() + ".provider", mFile);
            } else {
                imageUri = Uri.fromFile(mFile);
            }
            // 对目标应用临时授权该 Uri 所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // 将拍取的照片保存到指定 Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);
        } else {
            toast(R.string.photo_picture_error);
            finish();
        }
    } else {
        toast(R.string.photo_launch_fail);
        finish();
    }
}
 
Example #29
Source File: SourceEditActivity.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void shareSource(File file, String mediaType) {
    Uri contentUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", file);
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_STREAM, contentUri);
    intent.setType(mediaType);
    startActivity(Intent.createChooser(intent, "分享书源"));
}
 
Example #30
Source File: MailActivity.java    From AndroidAnimationExercise with Apache License 2.0 5 votes vote down vote up
private void sendMailWithApp() {
        File mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "one_api.txt");
        Uri mUri = null;


        Uri uri = Uri.parse("mailto:[email protected]");
        Intent mIntent = new Intent(Intent.ACTION_VIEW, uri);
//        mIntent.setType("message/rfc822");
        String[] tos = {"[email protected]"};
        mIntent.putExtra(Intent.EXTRA_EMAIL, tos);

        mIntent.putExtra(Intent.EXTRA_TEXT, "body");
        mIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mUri = FileProvider.getUriForFile(mContext, getPackageName() + ".fileprovider", mFile);
            // 申请临时访问权限
            mIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            mUri = Uri.parse(mFile.getAbsolutePath());
        }

        mIntent.putExtra(Intent.EXTRA_STREAM, mUri);
        Intent.createChooser(mIntent, "Choose Email Client");
        startActivity(mIntent);
    }