Example usage for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION

Introduction

In this page you can find the example usage for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION.

Prototype

int FLAG_GRANT_WRITE_URI_PERMISSION

To view the source code for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION.

Click Source Link

Document

If set, the recipient of this Intent will be granted permission to perform write operations on the URI in the Intent's data and any URIs specified in its ClipData.

Usage

From source file:io.github.pwlin.cordova.plugins.fileopener2.FileOpener2.java

private void _open(String fileArg, String contentType, CallbackContext callbackContext) throws JSONException {
    String fileName = "";
    try {//from   w ww. j  ava 2 s . c o m
        CordovaResourceApi resourceApi = webView.getResourceApi();
        Uri fileUri = resourceApi.remapUri(Uri.parse(fileArg));
        fileName = this.stripFileProtocol(fileUri.toString());
    } catch (Exception e) {
        fileName = fileArg;
    }
    File file = new File(fileName);
    if (file.exists()) {
        try {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24) {

                Context context = cordova.getActivity().getApplicationContext();
                path = FileProvider.getUriForFile(context,
                        cordova.getActivity().getPackageName() + ".opener.provider", file);
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                List<ResolveInfo> infoList = context.getPackageManager().queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : infoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, path,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
            /*
             * @see
             * http://stackoverflow.com/questions/14321376/open-an-activity-from-a-cordovaplugin
             */
            cordova.getActivity().startActivity(intent);
            //cordova.getActivity().startActivity(Intent.createChooser(intent,"Open File in..."));
            callbackContext.success();
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put("status", PluginResult.Status.ERROR.ordinal());
            errorObj.put("message", "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put("status", PluginResult.Status.ERROR.ordinal());
        errorObj.put("message", "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:com.commonsware.android.tte.DocumentStorageService.java

private void save(Uri document, String text, boolean isClosing) {
    boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

    try {/*from   w  w  w  .  j ava  2s .  co  m*/
        OutputStream os = getContentResolver().openOutputStream(document, "w");
        OutputStreamWriter osw = new OutputStreamWriter(os);

        try {
            osw.write(text);
            osw.flush();

            if (isClosing && isContent) {
                int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

                getContentResolver().releasePersistableUriPermission(document, perms);
            }

            EventBus.getDefault().post(new DocumentSavedEvent(document));
        } finally {
            osw.close();
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception saving " + document.toString(), e);
        EventBus.getDefault().post(new DocumentSaveErrorEvent(document, e));
    }
}

From source file:com.silentcircle.contacts.utils.ContactPhotoUtils19.java

/**
 * Adds common extras to gallery intents.
 *
 * @param intent The intent to add extras to.
 * @param photoUri The uri of the file to save the image to.
 *//*from w  w w.  ja  v a2s .  c  om*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void addPhotoPickerExtras(Intent intent, Uri photoUri) {
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, photoUri));
}

From source file:freed.ActivityAbstract.java

@TargetApi(VERSION_CODES.KITKAT)
@Override//from   w  w w .j av a 2 s  .  c o  m
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        // The document selected by the user won't be returned in the intent.
        // Instead, a URI to that document will be contained in the return intent
        // provided to this method as a parameter.
        // Pull that URI using resultData.getData().
        Uri uri = null;
        if (data != null) {
            uri = data.getData();
            int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.

            getContentResolver().takePersistableUriPermission(uri, takeFlags);
            appSettingsManager.SetBaseFolder(uri.toString());
            if (resultCallback != null) {
                resultCallback.onActivityResultCallback(uri);
                resultCallback = null;
            }
        }
    }
}

From source file:com.HumanDecisionSupportSystemsLaboratory.DD_P2P.SendPK.java

@SuppressLint("NewApi")
@Override/* w  w  w .  j  ava  2  s.c o  m*/
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == Activity.RESULT_OK && resultData != null) {
        Uri uri = null;

        if (requestCode == SELECT_PHOTO) {
            uri = resultData.getData();
            Log.i("Uri", "Uri: " + uri.toString());
        } else if (requestCode == SELECT_PHOTO_KITKAT) {
            uri = resultData.getData();
            Log.i("Uri_kitkat", "Uri: " + uri.toString());
            final int takeFlags = resultData.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getActivity().getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }

        selectedImagePath = FileUtils.getPath(getActivity(), uri);
        Log.i("path", "path: " + selectedImagePath);

        selectImageFile = new File(selectedImagePath);
        //File testFile = new File("file://storage/emulated/0/DCIM/hobbit.bmp");

        boolean success;

        String[] selected = new String[1];
        DD_Address adr = new DD_Address(peer);
        try {
            //util.EmbedInMedia.DEBUG = true;
            Log.i("success_embed", "success_embed 1: " + selectImageFile);
            success = DD.embedPeerInBMP(selectImageFile, selected, adr);
            Log.i("success_embed", "success_embed 2: " + success);
            if (success == true) {
                Toast.makeText(getActivity(), "Export success!", Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(getActivity(), "Unable to export:" + selected[0], Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getActivity(), "Unable to export!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }

    /*      if (resultCode == Activity.RESULT_OK && resultData != null) {
    Uri uri = null;
            
    if (requestCode == PK_SELECT_PHOTO) {
        uri = resultData.getData();
        Log.i("Uri", "Uri: " + uri.toString());
    } else if (requestCode == PK_SELECT_PHOTO_KITKAT) {
        uri = resultData.getData();
        Log.i("Uri_kitkat", "Uri: " + uri.toString());
        final int takeFlags = resultData.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.
        getActivity().getContentResolver().takePersistableUriPermission(uri, takeFlags);
    }
            
             
    selectedImagePath = FileUtils.getPath(getActivity(),uri);
    Log.i("path", "path: " + selectedImagePath); 
                
    selectImageFile = new File(selectedImagePath);
    //File testFile = new File("file://storage/emulated/0/DCIM/hobbit.bmp");
            
    boolean success;    
            
    try {
       //util.EmbedInMedia.DEBUG = true;
       success = saveSK(peer, selectImageFile);
       Log.i("success_embed", "success_embed: " + success); 
     if (success == true) {
         Toast.makeText(getActivity(), "Export success!", Toast.LENGTH_SHORT).show();
     } else 
         Toast.makeText(getActivity(), "Unable to export!", Toast.LENGTH_SHORT).show();  
    }
              catch (Exception e) {
     Toast.makeText(getActivity(), "Unable to export!", Toast.LENGTH_SHORT).show();
     e.printStackTrace();
              } 
                   
          }*/
    super.onActivityResult(requestCode, resultCode, resultData);
}

From source file:com.android.browser.UploadHandler.java

private Intent createCameraIntent(Uri contentUri) {
    if (contentUri == null)
        throw new IllegalArgumentException();
    mCapturedMedia = contentUri;// w  w  w  . j  a  va  2s.  c  o m
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedMedia);
    intent.setClipData(ClipData.newUri(mController.getActivity().getContentResolver(), FILE_PROVIDER_AUTHORITY,
            mCapturedMedia));
    return intent;
}

From source file:cz.maresmar.sfm.app.SfmApp.java

private void sendFeedback(Context context, String subject) {
    Timber.i("Device %s (%s) on SDK %d", Build.DEVICE, Build.MANUFACTURER, Build.VERSION.SDK_INT);

    File logFile = getLogFile();/*  w  ww.java2 s.  c  o  m*/
    Uri logUri = FileProvider.getUriForFile(this, "cz.maresmar.sfm.FileProvider", logFile);

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "mmrmartin+dev" + '@' + "gmail.com" });
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[sfm] " + subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.feedback_mail_text));
    emailIntent.putExtra(Intent.EXTRA_STREAM, logUri);
    emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(emailIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, logUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    context.startActivity(
            Intent.createChooser(emailIntent, getString(R.string.feedback_choose_email_app_dialog)));
}

From source file:com.jefftharris.passwdsafe.StorageFileListFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_file_open: {
        startOpenFile();//  w  w w  .  ja  v a 2 s  .  co m
        return true;
    }
    case R.id.menu_file_new: {
        startActivity(new Intent(PasswdSafeUtil.NEW_INTENT));
        return true;
    }
    case R.id.menu_clear_recent: {
        try {
            ContentResolver cr = getActivity().getContentResolver();
            int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            Cursor cursor = itsRecentFilesDb.queryFiles();
            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        Uri uri = Uri.parse(cursor.getString(RecentFilesDb.QUERY_COL_URI));
                        ApiCompat.releasePersistableUriPermission(cr, uri, flags);
                    }
                } finally {
                    cursor.close();
                }
            }
            itsRecentFilesDb.clear();

            List<Uri> permUris = ApiCompat.getPersistedUriPermissions(cr);
            for (Uri permUri : permUris) {
                ApiCompat.releasePersistableUriPermission(cr, permUri, flags);
            }

            getLoaderManager().restartLoader(LOADER_FILES, null, this);
        } catch (Exception e) {
            PasswdSafeUtil.showFatalMsg(e, "Clear recent error", getActivity());
        }
        return true;
    }
    default: {
        return super.onOptionsItemSelected(item);
    }
    }
}

From source file:com.just.agentweb.AgentWebUtils.java

static void setIntentDataAndType(Context context, Intent intent, String type, File file, boolean writeAble) {
    if (Build.VERSION.SDK_INT >= 24) {
        intent.setDataAndType(getUriFromFile(context, file), type);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (writeAble) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }/* w w w  .  ja v a 2 s  . c o m*/
    } else {
        intent.setDataAndType(Uri.fromFile(file), type);
    }
}

From source file:java_lang_programming.com.android_media_demo.ImageSelectionCropDemo.java

/**
 * start Crop//from  ww  w  .j  a  va2 s .  co m
 *
 * @param uri image uri
 */
private void startCrop(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("aspectX", 16);
    intent.putExtra("aspectY", 9);
    intent.putExtra("scaleUpIfNeeded", true);
    intent.putExtra("scale", "true");
    intent.putExtra("return-data", false);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.name());
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getExternalStorageTempStoreFilePath()));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    startActivityForResult(intent, ImageSelectionCropDemo.REQUEST_CODE_CROP);
}