Example usage for android.content ContentResolver SCHEME_FILE

List of usage examples for android.content ContentResolver SCHEME_FILE

Introduction

In this page you can find the example usage for android.content ContentResolver SCHEME_FILE.

Prototype

String SCHEME_FILE

To view the source code for android.content ContentResolver SCHEME_FILE.

Click Source Link

Usage

From source file:com.mediatek.galleryfeature.stereo.segment.background.StereoBackgroundActivity.java

private boolean finishIfInvalidUri() {
    if (!mNeedCheckInvalid) {
        return false;
    }/*from  ww w.j  av  a2  s .  c  om*/
    Uri uri = (mMasterImage != null) ? mMasterImage.getUri() : null;
    Intent intent = getIntent();
    if ((uri == null) && (intent != null)) {
        uri = intent.getData();
    }
    MtkLog.d(TAG, "<finishIfInvalidUri> uri:" + uri);
    if (uri != null) {
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return false;
        }
        // fix cursor leak
        final String[] projection = new String[] { ImageColumns.DATA, ImageColumns.CAMERA_REFOCUS };
        android.database.Cursor cursor = null;
        cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) {
            MtkLog.d(TAG, "<finishIfInvalidUri> cannot get cursor for:" + uri);
            return true;
        }
        try {
            if (cursor.moveToNext()) {
                mAbsoluteFilePath = cursor.getString(0);
                MtkLog.d(TAG, "<finishIfInvalidUri> mAbsoluteFilePath = " + mAbsoluteFilePath);
                mIsDepthImage = (cursor.getInt(1) == 1);
                MtkLog.d(TAG, "<finishIfInvalidUri> mIsDepthImage = " + mIsDepthImage);
            } else {
                MtkLog.d(TAG, "<finishIfInvalidUri> cannot find data for: " + uri);
                return true;
            }
        } finally {
            cursor.close();
        }
    }
    return false;
}

From source file:com.android.providers.downloads.DownloadInfo.java

/**
 * Returns whether this download should be enqueued.
 *//*  ww  w.j av  a  2 s. c  o m*/
private boolean isReadyToDownload() {
    if (mControl == Downloads.Impl.CONTROL_PAUSED) {
        // the download is paused, so it's not going to start
        Log.i(Constants.DL_ENHANCE, "Download is paused " + "then no need to start");
        return false;
    }
    switch (mStatus) {
    case 0: // status hasn't been initialized yet, this is a new download
    case Downloads.Impl.STATUS_PENDING: // download is explicit marked as ready to start
    case Downloads.Impl.STATUS_RUNNING: // download interrupted (process killed etc) while
                                        // running, without a chance to update the database
        return true;

    case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
    case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
        return checkCanUseNetwork(mTotalBytes) == NetworkState.OK;

    case Downloads.Impl.STATUS_WAITING_TO_RETRY:
        // download was waiting for a delayed restart
        final long now = mSystemFacade.currentTimeMillis();
        return restartTime(now) <= now;
    case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
        // is the media mounted?
        final Uri uri = Uri.parse(mUri);
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            final File file = new File(uri.getPath());
            return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(file));
        } else {
            Log.w(TAG, "Expected file URI on external storage: " + mUri);
            return false;
        }
        /// M: Because OMA DL spec, if insufficient memory, we
        /// will show to user but not retry.
        //case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
        // should check space to make sure it is worth retrying the download.
        // but thats the first thing done by the thread when it retries to download
        // it will fail pretty quickly if there is no space.
        // so, it is not that bad to skip checking space availability here.
        //return true;
        /// M: Add for fix alp00406729, file already exist but user do not operation. @{
    case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
        return false;
    /// @}
    }
    return false;
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static boolean isValidUriTarget(String data) {
    if (data == null) {
        Log.d(TAG, "uri is null");
        return false;
    } else if (data.startsWith(ContentResolver.SCHEME_CONTENT)) {
        Log.d(TAG, "checking content uri");
        return isValidUri(Uri.parse(data));
    } else if (data.startsWith(ContentResolver.SCHEME_FILE)) {
        try {/*from   ww w . j ava2 s.c  o m*/
            Log.d(TAG, "checking file uri");
            return new File(URI.create(data)).exists();
        } catch (IllegalArgumentException e) {
            // We have received wrong uri. Failed upload shall be cleaned up.
            return false;
        }
    } else if (new File(data).exists()) {
        return true;
    } else {
        Log.e(TAG, "unknown uri: " + data);
    }
    return false;
}

From source file:org.sufficientlysecure.keychain.ui.DecryptListFragment.java

/**
 * Request READ_EXTERNAL_STORAGE permission on Android >= 6.0 to read content from "file" Uris.
 * <p/>//from   w w  w.jav a 2s. c  o  m
 * This method returns true on Android < 6, or if permission is already granted. It
 * requests the permission and returns false otherwise, taking over responsibility
 * for mCurrentInputUri.
 * <p/>
 * see https://commonsware.com/blog/2015/10/07/runtime-permissions-files-action-send.html
 */
private boolean checkAndRequestReadPermission(Activity activity, final Uri uri) {
    if (!ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
        return true;
    }

    // Additional check due to https://commonsware.com/blog/2015/11/09/you-cannot-hold-nonexistent-permissions.html
    if (Build.VERSION.SDK_INT < VERSION_CODES.M) {
        return true;
    }

    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }

    requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
            REQUEST_PERMISSION_READ_EXTERNAL_STORAGE);

    return false;

}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

/**
 * For a given file {@link Uri} string, we check if its hash has a
 * corresponding entry in the {@link MetaProvider}, telling thus whether the
 * file from under given {@link Uri} string has been already uploaded.
 * //from ww w . j av a 2 s.com
 * @param uriString
 *            the uri string which content we are checking
 * @return resourcePath if content under uri has been already uploaded,
 *         null otherwise
 */
public static String isUploaded(String uriString) {
    File file = null;
    String fileHash = null;

    if (uriString.startsWith(ContentResolver.SCHEME_CONTENT)) {
        final String[] projection = new String[] { MediaColumns.DATA };
        final Cursor c = sResolver.query(Uri.parse(uriString), projection, null, null, null);
        try {
            if (c.moveToFirst()) {
                String data = c.getString(c.getColumnIndex(MediaColumns.DATA));
                file = new File(data);
            } else {
                return null;
            }
        } finally {
            c.close();
        }
    } else if (uriString.startsWith(ContentResolver.SCHEME_FILE)) {
        final URI fileURI = URI.create(Uri.encode(uriString, ":/"));
        file = new File(fileURI);
    } else {
        Log.e(TAG, "Tried to check malformed uri string: " + uriString);
        return null;
    }

    try {
        if (file != null && file.exists()) {
            fileHash = HashUtils.getSha1(file);
            Log.d(TAG, String.format("Computed hash: '%s'", fileHash));
        } else {
            throw new FileNotFoundException("isUploaded()");
        }
    } catch (Exception e) {
        Log.e(TAG, "Can't compute file hash!", e);
        return null;
    }

    final String[] projection = new String[] { Nodes.NODE_RESOURCE_PATH };
    final String selection = Nodes.NODE_HASH + "=?";
    final String[] selectionArgs = new String[] { fileHash };
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    String resourcePath = null;
    try {
        if (c.moveToFirst()) {
            resourcePath = c.getString(c.getColumnIndex(Nodes.NODE_RESOURCE_PATH));
            Log.d(TAG, "Corresponding file hash found: " + resourcePath);
        } else {
            Log.d(TAG, "Corresponding file hash not found.");
        }
    } finally {
        c.close();
    }
    return resourcePath;
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

private String getIconUriString(Source source, String drawableId) {
    // Fast path for empty icons
    if (TextUtils.isEmpty(drawableId) || "0".equals(drawableId)) {
        return null;
    }//from  w ww .  ja  v a2 s. c  om
    // Fast path for icon URIs
    if (drawableId.startsWith(ContentResolver.SCHEME_ANDROID_RESOURCE)
            || drawableId.startsWith(ContentResolver.SCHEME_CONTENT)
            || drawableId.startsWith(ContentResolver.SCHEME_FILE)) {
        return drawableId;
    }
    Uri uri = source.getIconUri(drawableId);
    return uri == null ? null : uri.toString();
}

From source file:org.sufficientlysecure.keychain.ui.DecryptListFragment.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {

    if (requestCode != REQUEST_PERMISSION_READ_EXTERNAL_STORAGE) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;/*ww  w .j  a v  a 2  s .  com*/
    }

    boolean permissionWasGranted = grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED;

    if (permissionWasGranted) {

        // permission granted -> retry all cancelled file uris
        Iterator<Uri> it = mCancelledInputUris.iterator();
        while (it.hasNext()) {
            Uri uri = it.next();
            if (!ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
                continue;
            }
            it.remove();
            mPendingInputUris.add(uri);
            mAdapter.setCancelled(uri, false);
        }

    } else {

        // permission denied -> cancel current, and all pending file uris
        mCancelledInputUris.add(mCurrentInputUri);
        mAdapter.setCancelled(mCurrentInputUri, true);

        mCurrentInputUri = null;
        Iterator<Uri> it = mPendingInputUris.iterator();
        while (it.hasNext()) {
            Uri uri = it.next();
            if (!ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
                continue;
            }
            it.remove();
            mCancelledInputUris.add(uri);
            mAdapter.setCancelled(uri, true);
        }

    }

    // hand control flow back
    cryptoOperation();

}

From source file:com.android.messaging.mmslib.pdu.PduPersister.java

/**
 * This method expects uri in the following format
 *     content://media/<table_name>/<row_index> (or)
 *     file://sdcard/test.mp4//from  w  ww  . j a v  a 2 s.c o  m
 *     http://test.com/test.mp4
 *
 * Here <table_name> shall be "video" or "audio" or "images"
 * <row_index> the index of the content in given table
 */
public static String convertUriToPath(final Context context, final Uri uri) {
    String path = null;
    if (null != uri) {
        final String scheme = uri.getScheme();
        if (null == scheme || scheme.equals("") || scheme.equals(ContentResolver.SCHEME_FILE)) {
            path = uri.getPath();

        } else if (scheme.equals("http")) {
            path = uri.toString();

        } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            final String[] projection = new String[] { MediaStore.MediaColumns.DATA };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
                    throw new IllegalArgumentException("Given Uri could not be found" + " in media store");
                }
                final int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                path = cursor.getString(pathIndex);
            } catch (final SQLiteException e) {
                throw new IllegalArgumentException(
                        "Given Uri is not formatted in a way " + "so that it can be found in media store.");
            } finally {
                if (null != cursor) {
                    cursor.close();
                }
            }
        } else {
            throw new IllegalArgumentException("Given Uri scheme is not supported");
        }
    }
    return path;
}

From source file:org.mariotaku.harmony.MusicPlaybackService.java

/**
 * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The
 * intent will call closeExternalStorageFiles() if the external media is
 * going to be ejected, so applications can clean up any files they have
 * open./*from   w ww . jav  a2  s .com*/
 */
public void registerExternalStorageListener() {
    if (mUnmountReceiver == null) {
        mUnmountReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();
                if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
                    saveQueue(true);
                    mQueueIsSaveable = false;
                    closeExternalStorageFiles(intent.getData().getPath());
                } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                    mCardId = MusicUtils.getCardId(context);
                    reloadQueue();
                    mQueueIsSaveable = true;
                    notifyChange(BROADCAST_QUEUE_CHANGED);
                    notifyChange(BROADCAST_MEDIA_CHANGED);
                }
            }
        };
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addDataScheme(ContentResolver.SCHEME_FILE);
        registerReceiver(mUnmountReceiver, filter);
    }
}

From source file:com.amaze.filemanager.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    if (materialDialog != null && !materialDialog.isShowing()) {
        materialDialog.show();/*from   w w  w. j a v a 2s  .  c  o m*/
        materialDialog = null;
    }
    IntentFilter newFilter = new IntentFilter();
    newFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    newFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    newFilter.addDataScheme(ContentResolver.SCHEME_FILE);
    registerReceiver(mainActivityHelper.mNotificationReceiver, newFilter);
    registerReceiver(receiver2, new IntentFilter("general_communications"));
    if (getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getName()
            .contains("TabFragment")) {

        floatingActionButton.setVisibility(View.VISIBLE);
        floatingActionButton.showMenuButton(false);
    } else {

        floatingActionButton.setVisibility(View.INVISIBLE);
        floatingActionButton.hideMenuButton(false);
    }
}