Java Code Examples for android.content.res.AssetFileDescriptor#createInputStream()

The following examples show how to use android.content.res.AssetFileDescriptor#createInputStream() . 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: ContactPhotoQuery.java    From flutter_sms with MIT License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.ECLAIR)
private void queryContactPhoto() {
  Uri uri = Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, photoUri);

  try {
    AssetFileDescriptor fd = registrar.context().getContentResolver().openAssetFileDescriptor(
        uri, "r");
    if (fd != null) {
      InputStream stream = fd.createInputStream();
      byte[] bytes = getBytesFromInputStream(stream);
      stream.close();
      result.success(bytes);
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 2
Source File: FilePathHelper.java    From qcloud-sdk-android-samples with MIT License 6 votes vote down vote up
private static InputStream getInputStreamForVirtualFile(Context context, Uri uri)
        throws IOException {

    ContentResolver resolver = context.getContentResolver();

    String[] openableMimeTypes = resolver.getStreamTypes(uri, "*/*");

    if (openableMimeTypes == null ||
            openableMimeTypes.length < 1) {
        throw new FileNotFoundException();
    }

    AssetFileDescriptor assetFileDescriptor = resolver.openAssetFileDescriptor(uri, openableMimeTypes[0], null);
    if (assetFileDescriptor == null) {
        throw new IOException("open virtual file failed");
    }
    return assetFileDescriptor.createInputStream();
}
 
Example 3
Source File: SystemServices.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
public static FileInfo getContactAsVCardFile(Context context, Uri uri) {
    AssetFileDescriptor fd;
    try {
        fd = context.getContentResolver().openAssetFileDescriptor(uri, "r");
        java.io.FileInputStream in = fd.createInputStream();
        byte[] buf = new byte[(int) fd.getDeclaredLength()];
        in.read(buf);
        in.close();
        String vCardText = new String(buf);
        Log.d("Vcard", vCardText);
        List<String> pathSegments = uri.getPathSegments();
        String targetPath = "/" + pathSegments.get(pathSegments.size() - 1) + ".vcf";
        SecureMediaStore.copyToVfs(buf, targetPath);
        FileInfo info = new FileInfo();
        info.stream = new info.guardianproject.iocipher.FileInputStream(SecureMediaStore.vfsUri(targetPath).getPath());
        info.type = "text/vcard";
        return info;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 4
Source File: SliceTestActivity.java    From incubator-weex-playground with Apache License 2.0 5 votes vote down vote up
private byte[] loadBytes() {
  try {
    AssetFileDescriptor assetFileDescriptor = getAssets().openFd("lite_template/card.wasm");
    long len = assetFileDescriptor.getDeclaredLength();
    ByteBuffer buf = ByteBuffer.allocate((int) len);
    InputStream json = assetFileDescriptor.createInputStream();
    json.read(buf.array());
    json.close();
    return buf.array();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 5
Source File: ContentResolver.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Open a stream on to the content associated with a content URI.  If there
 * is no data associated with the URI, FileNotFoundException is thrown.
 *
 * <h5>Accepts the following URI schemes:</h5>
 * <ul>
 * <li>content ({@link #SCHEME_CONTENT})</li>
 * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
 * <li>file ({@link #SCHEME_FILE})</li>
 * </ul>
 *
 * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
 * on these schemes.
 *
 * @param uri The desired URI.
 * @return InputStream
 * @throws FileNotFoundException if the provided URI could not be opened.
 * @see #openAssetFileDescriptor(Uri, String)
 */
public final @Nullable InputStream openInputStream(@NonNull Uri uri)
        throws FileNotFoundException {
    Preconditions.checkNotNull(uri, "uri");
    String scheme = uri.getScheme();
    if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        OpenResourceIdResult r = getResourceId(uri);
        try {
            InputStream stream = r.r.openRawResource(r.id);
            return stream;
        } catch (Resources.NotFoundException ex) {
            throw new FileNotFoundException("Resource does not exist: " + uri);
        }
    } else if (SCHEME_FILE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        return new FileInputStream(uri.getPath());
    } else {
        AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null);
        try {
            return fd != null ? fd.createInputStream() : null;
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to create stream");
        }
    }
}
 
Example 6
Source File: ContentResolver.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Open a stream on to the content associated with a content URI.  If there
 * is no data associated with the URI, FileNotFoundException is thrown.
 *
 * <h5>Accepts the following URI schemes:</h5>
 * <ul>
 * <li>content ({@link #SCHEME_CONTENT})</li>
 * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
 * <li>file ({@link #SCHEME_FILE})</li>
 * </ul>
 *
 * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
 * on these schemes.
 *
 * @param uri The desired URI.
 * @return InputStream
 * @throws FileNotFoundException if the provided URI could not be opened.
 * @see #openAssetFileDescriptor(Uri, String)
 */
public final @Nullable InputStream openInputStream(@NonNull Uri uri)
        throws FileNotFoundException {
    Preconditions.checkNotNull(uri, "uri");
    String scheme = uri.getScheme();
    if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        OpenResourceIdResult r = getResourceId(uri);
        try {
            InputStream stream = r.r.openRawResource(r.id);
            return stream;
        } catch (Resources.NotFoundException ex) {
            throw new FileNotFoundException("Resource does not exist: " + uri);
        }
    } else if (SCHEME_FILE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        return new FileInputStream(uri.getPath());
    } else {
        AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null);
        try {
            return fd != null ? fd.createInputStream() : null;
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to create stream");
        }
    }
}
 
Example 7
Source File: ContentResolver.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Open a stream on to the content associated with a content URI.  If there
 * is no data associated with the URI, FileNotFoundException is thrown.
 *
 * <h5>Accepts the following URI schemes:</h5>
 * <ul>
 * <li>content ({@link #SCHEME_CONTENT})</li>
 * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
 * <li>file ({@link #SCHEME_FILE})</li>
 * </ul>
 *
 * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
 * on these schemes.
 *
 * @param uri The desired URI.
 * @return InputStream
 * @throws FileNotFoundException if the provided URI could not be opened.
 * @see #openAssetFileDescriptor(Uri, String)
 */
public final @Nullable InputStream openInputStream(@NonNull Uri uri)
        throws FileNotFoundException {
    Preconditions.checkNotNull(uri, "uri");
    String scheme = uri.getScheme();
    if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        OpenResourceIdResult r = getResourceId(uri);
        try {
            InputStream stream = r.r.openRawResource(r.id);
            return stream;
        } catch (Resources.NotFoundException ex) {
            throw new FileNotFoundException("Resource does not exist: " + uri);
        }
    } else if (SCHEME_FILE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        return new FileInputStream(uri.getPath());
    } else {
        AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null);
        try {
            return fd != null ? fd.createInputStream() : null;
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to create stream");
        }
    }
}
 
Example 8
Source File: FileUtil.java    From GetApk with MIT License 5 votes vote down vote up
public static void copy(ContentResolver resolver, Uri source, Uri dest, OnCopyListener listener) throws IOException {

        FileInputStream in = null;
        OutputStream out = null;
        try{
            AssetFileDescriptor fd = resolver.openAssetFileDescriptor(source, "r");
            in =  fd != null ? fd.createInputStream() : null;

            if (in == null){
                throw new IOException("open the src file failed");
            }
            long total = fd.getLength();
            long sum = 0;

            out = resolver.openOutputStream(dest);

            if (out == null) {
                throw new IOException("open the dest file failed");
            }
            // Transfer bytes from in to out
            byte[] buf = new byte[1024 * 4];
            int len;
            Thread thread = Thread.currentThread();
            while ((len = in.read(buf)) > 0) {
                if (thread.isInterrupted()) {
                    break;
                }
                sum += len;
                out.write(buf, 0, len);
                if (listener != null) {
                    listener.inProgress(sum * 1.0f / total);
                }
            }
        }finally {
            IOUtil.closeQuiet(in);
            IOUtil.closeQuiet(out);
        }
    }
 
Example 9
Source File: SafeContentResolver.java    From SafeContentResolver with Apache License 2.0 5 votes vote down vote up
/**
 * Open a stream to the content associated with a URI.
 *
 * <p>
 * If the provided URI is not a {@code file://} URI, {@link ContentResolver#openInputStream(Uri)} is used to open a
 * stream. If it is a {@code file://}, this method makes sure the file isn't owned by this app.
 * </p>
 *
 * @param uri
 *         The URI pointing to the content to access.
 *
 * @return {@code InputStream} to access the content.
 *
 * @throws FileNotFoundException
 *         If the provided URI could not be opened or if it points to a file owned by this app.
 */
@Nullable
public InputStream openInputStream(@NotNull Uri uri) throws FileNotFoundException {
    //noinspection ConstantConditions
    if (uri == null) {
        throw new NullPointerException("Argument 'uri' must not be null");
    }

    String scheme = uri.getScheme();
    if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
        String authority = uri.getAuthority();
        if (disallowedProviders.isDisallowed(authority)) {
            throw new FileNotFoundException("content URI is owned by the application itself. " +
                    "Content provider is not explicitly allowed: " + authority);
        }
    }

    if (!ContentResolver.SCHEME_FILE.equals(scheme)) {
        return contentResolver.openInputStream(uri);
    }

    File file = new File(uri.getPath());
    ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

    int fileUid = getFileUidOrThrow(fileDescriptor);
    if (fileUid == android.os.Process.myUid()) {
        throw new FileNotFoundException("File is owned by the application itself");
    }

    AssetFileDescriptor fd = new AssetFileDescriptor(parcelFileDescriptor, 0, -1);
    try {
        return fd.createInputStream();
    } catch (IOException e) {
        throw new FileNotFoundException("Unable to create stream");
    }
}
 
Example 10
Source File: ProfileOwnerService.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
@Override
public boolean installCaCertificate(AssetFileDescriptor afd) {
    try (FileInputStream fis = afd.createInputStream()) {
        return Util.installCaCertificate(fis, mDpm, DeviceAdminReceiver.getComponentName(
                mContext));
    } catch (IOException e) {
        Log.e(TAG, "Unable to install a certificate", e);
        return false;
    }
}
 
Example 11
Source File: LocalContentUriFetchProducer.java    From fresco with MIT License 5 votes vote down vote up
@Override
protected EncodedImage getEncodedImage(ImageRequest imageRequest) throws IOException {
  Uri uri = imageRequest.getSourceUri();
  if (UriUtil.isLocalContactUri(uri)) {
    final InputStream inputStream;
    if (uri.toString().endsWith("/photo")) {
      inputStream = mContentResolver.openInputStream(uri);
    } else if (uri.toString().endsWith("/display_photo")) {
      try {
        AssetFileDescriptor fd = mContentResolver.openAssetFileDescriptor(uri, "r");
        inputStream = fd.createInputStream();
      } catch (IOException e) {
        throw new IOException("Contact photo does not exist: " + uri);
      }
    } else {
      inputStream = ContactsContract.Contacts.openContactPhotoInputStream(mContentResolver, uri);
      if (inputStream == null) {
        throw new IOException("Contact photo does not exist: " + uri);
      }
    }
    // If a Contact URI is provided, use the special helper to open that contact's photo.
    return getEncodedImage(inputStream, EncodedImage.UNKNOWN_STREAM_SIZE);
  }

  if (UriUtil.isLocalCameraUri(uri)) {
    EncodedImage cameraImage = getCameraImage(uri);
    if (cameraImage != null) {
      return cameraImage;
    }
  }

  return getEncodedImage(mContentResolver.openInputStream(uri), EncodedImage.UNKNOWN_STREAM_SIZE);
}
 
Example 12
Source File: ContactHelper.java    From NotificationPeekPort with Apache License 2.0 5 votes vote down vote up
/**
 * Get the InputStream object of the contact photo with given contact ID.
 *
 * @param context       Context object of the caller.
 * @param contactId     Contact ID.
 * @return              InputStream object of the contact photo.
 */
public static InputStream openDisplayPhoto(Context context, long contactId) {
    Uri contactUri =
            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
    Uri displayPhotoUri =
            Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
    try {
        AssetFileDescriptor fd =
                context.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
        return fd.createInputStream();
    } catch (IOException e) {
        return null;
    }
}
 
Example 13
Source File: CheapAMR.java    From MusicPlayer with GNU General Public License v3.0 4 votes vote down vote up
public void readFile(Uri inputFile)
        throws java.io.FileNotFoundException,
        java.io.IOException {
    super.readFile(inputFile);
    mNumFrames = 0;
    mMaxFrames = 64;  // This will grow as needed
    mFrameGains = new int[mMaxFrames];
    mMinGain = 1000000000;
    mMaxGain = 0;
    mBitRate = 10;
    mOffset = 0;

    InputStream stream = null;
    AssetFileDescriptor file;
    file = App.getInstance().getContentResolver().openAssetFileDescriptor(inputFile, "r");

    if(file == null) throw  new NullPointerException("File is null");

    stream = file.createInputStream();
    if(stream == null) throw new NullPointerException("Input stream is null");

    else Log.d("audioSeekbar", "ReadFile: input stream is not null");

    // No need to handle filesizes larger than can fit in a 32-bit int
    mFileSize = (int) file.getLength();

    if (mFileSize < 128) {
        throw new java.io.IOException("File too small to parse");
    }

    byte[] header = new byte[12];
    stream.read(header, 0, 6);
    mOffset += 6;
    if (header[0] == '#' &&
            header[1] == '!' &&
            header[2] == 'A' &&
            header[3] == 'M' &&
            header[4] == 'R' &&
            header[5] == '\n') {
        parseAMR(stream, mFileSize - 6);
    }

    stream.read(header, 6, 6);
    mOffset += 6;

    if (header[4] == 'f' &&
            header[5] == 't' &&
            header[6] == 'y' &&
            header[7] == 'p' &&
            header[8] == '3' &&
            header[9] == 'g' &&
            header[10] == 'p' &&
            header[11] == '4') {

        int boxLen =
                ((0xff & header[0]) << 24) |
                        ((0xff & header[1]) << 16) |
                        ((0xff & header[2]) << 8) |
                        ((0xff & header[3]));

        if (boxLen >= 4 && boxLen <= mFileSize - 8) {
            stream.skip(boxLen - 12);
            mOffset += boxLen - 12;
        }

        parse3gpp(stream, mFileSize - boxLen);
    }
}
 
Example 14
Source File: CheapWAV.java    From MusicPlayer with GNU General Public License v3.0 4 votes vote down vote up
public void readFile(Uri inputFile) throws java.io.IOException {
    super.readFile(inputFile);

    InputStream stream = null;
    AssetFileDescriptor file;
    file = App.getInstance().getContentResolver().openAssetFileDescriptor(inputFile, "r");

    if(file == null) throw  new NullPointerException("File is null");

    stream = file.createInputStream();
    if(stream == null) throw new NullPointerException("Input stream is null");

    else Log.d("audioSeekbar", "ReadFile: input stream is not null");

    // No need to handle filesizes larger than can fit in a 32-bit int
    mFileSize = (int) file.getLength();

    if (mFileSize < 128) {
        throw new java.io.IOException("File too small to parse");
    }
    try {
        WavFileDescriptor wavFile = WavFileDescriptor.openWavFile(file);
        mNumFrames = (int) (wavFile.getNumFrames() / getSamplesPerFrame());
        mFrameGains = new int[mNumFrames];
        mSampleRate = (int) wavFile.getSampleRate();
        mChannels = wavFile.getNumChannels();

        int gain, value;
        int[] buffer = new int[getSamplesPerFrame()];
        for (int i = 0; i < mNumFrames; i++) {
            gain = -1;
            wavFile.readFrames(buffer, getSamplesPerFrame());
            for (int j = 0; j < getSamplesPerFrame(); j++) {
                value = buffer[j];
                if (gain < value) {
                    gain = value;
                }
            }
            mFrameGains[i] = (int) Math.sqrt(gain);
            if (mProgressListener != null) {
                boolean keepGoing = mProgressListener.reportProgress(i * 1.0 / mFrameGains.length);
                if (!keepGoing) {
                    break;
                }
            }
        }
        if (wavFile != null) {
            wavFile.close();
        }
    } catch (WavFileException e) {
        Log.e(TAG, "Exception while reading wav file", e);
    }
}
 
Example 15
Source File: CheapAAC.java    From MusicPlayer with GNU General Public License v3.0 4 votes vote down vote up
public void readFile(Uri inputFile)
        throws java.io.FileNotFoundException,
        java.io.IOException {
    super.readFile(inputFile);
    mChannels = 0;
    mSampleRate = 0;
    mBitrate = 0;
    mSamplesPerFrame = 0;
    mNumFrames = 0;
    mMinGain = 255;
    mMaxGain = 0;
    mOffset = 0;
    mMdatOffset = -1;
    mMdatLength = -1;

    mAtomMap = new HashMap<Integer, Atom>();

    InputStream stream = null;
    AssetFileDescriptor file;
    file = App.getInstance().getContentResolver().openAssetFileDescriptor(inputFile, "r");

    if(file == null) throw  new NullPointerException("File is null");

    // Read the first 8 bytes
    stream = file.createInputStream();
    if(stream == null) throw new NullPointerException("Input stream is null");

    else Log.d("audioSeekbar", "ReadFile: input stream is not null");

    // No need to handle filesizes larger than can fit in a 32-bit int
    mFileSize = (int) file.getLength();

    if (mFileSize < 128) {
        throw new java.io.IOException("File too small to parse");
    }

    byte[] header = new byte[8];
    stream.read(header, 0, 8);

    if (header[0] == 0 &&
            header[4] == 'f' &&
            header[5] == 't' &&
            header[6] == 'y' &&
            header[7] == 'p') {
        // Create a new stream, reset to the beginning of the file
        stream = file.createInputStream();
        parseMp4(stream, mFileSize);
    } else {
        throw new java.io.IOException("Unknown file format");
    }

    if (mMdatOffset > 0 && mMdatLength > 0) {
        stream = file.createInputStream();
        stream.skip(mMdatOffset);
        mOffset = mMdatOffset;
        parseMdat(stream, mMdatLength);
    } else {
        throw new java.io.IOException("Didn't find mdat");
    }

    boolean bad = false;
    for (int requiredAtomType : kRequiredAtoms) {
        if (!mAtomMap.containsKey(requiredAtomType)) {
            System.out.println("Missing atom: " +
                    atomToString(requiredAtomType));
            bad = true;
        }
    }

    if (bad) {
        throw new java.io.IOException("Could not parse MP4 file");
    }
}