Java Code Examples for android.content.res.AssetFileDescriptor#getLength()
The following examples show how to use
android.content.res.AssetFileDescriptor#getLength() .
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: Helper.java From VIA-AI with MIT License | 6 votes |
public static void findAPKFile(String filepath, Context context) { String apkFilepath = getAPKFilepath(context); // Get the offset and length for the file: theUrl, that is in your // assets folder AssetManager assetManager = context.getAssets(); try { AssetFileDescriptor assFD = assetManager.openFd(filepath); if (assFD != null) { long offset = assFD.getStartOffset(); long fileSize = assFD.getLength(); assFD.close(); // **** offset and fileSize are the offset and size // **** in bytes of the asset inside the APK } } catch (IOException e) { e.printStackTrace(); } }
Example 2
Source File: NativeVorbisLoader.java From jmonkeyengine with BSD 3-Clause "New" or "Revised" License | 6 votes |
private static AudioBuffer loadBuffer(AssetInfo assetInfo) throws IOException { AndroidAssetInfo aai = (AndroidAssetInfo) assetInfo; AssetFileDescriptor afd = null; NativeVorbisFile file = null; try { afd = aai.openFileDescriptor(); int fd = afd.getParcelFileDescriptor().getFd(); file = new NativeVorbisFile(fd, afd.getStartOffset(), afd.getLength()); ByteBuffer data = BufferUtils.createByteBuffer(file.totalBytes); file.readFully(data); AudioBuffer ab = new AudioBuffer(); ab.setupFormat(file.channels, 16, file.sampleRate); ab.updateData(data); return ab; } finally { if (file != null) { file.close(); } if (afd != null) { afd.close(); } } }
Example 3
Source File: LocalAssetFetchProducer.java From fresco with MIT License | 6 votes |
private int getLength(ImageRequest imageRequest) { AssetFileDescriptor fd = null; try { fd = mAssetManager.openFd(getAssetName(imageRequest)); return (int) fd.getLength(); } catch (IOException e) { return -1; } finally { try { if (fd != null) { fd.close(); } } catch (IOException ignored) { // There's nothing we can do with the exception when closing descriptor. } } }
Example 4
Source File: LocalResourceFetchProducer.java From fresco with MIT License | 6 votes |
private int getLength(ImageRequest imageRequest) { AssetFileDescriptor fd = null; try { fd = mResources.openRawResourceFd(getResourceId(imageRequest)); return (int) fd.getLength(); } catch (Resources.NotFoundException e) { return -1; } finally { try { if (fd != null) { fd.close(); } } catch (IOException ignored) { // There's nothing we can do with the exception when closing descriptor. } } }
Example 5
Source File: AFDStrategy.java From cwac-provider with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public long getLength(Uri uri) { AssetFileDescriptor afd; long result=super.getLength(uri); try { afd=getAssetFileDescriptor(uri); result=afd.getLength(); afd.close(); } catch (Exception e) { Log.w(getClass().getSimpleName(), "Exception getting asset length", e); } return(result); }
Example 6
Source File: LocalResourceFetchProducer.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
@Override protected int getLength(ImageRequest imageRequest) { AssetFileDescriptor fd = null; try { fd = mResources.openRawResourceFd(getResourceId(imageRequest)); return (int) fd.getLength(); } catch (Resources.NotFoundException e) { return -1; } finally { try { if (fd != null) { fd.close(); } } catch (IOException ignored) { // There's nothing we can do with the exception when closing descriptor. } } }
Example 7
Source File: AbstractTest.java From cloudinary_android with MIT License | 6 votes |
protected static long getAssetFileSize(String filename) { AssetFileDescriptor assetFileDescriptor = null; try { assetFileDescriptor = InstrumentationRegistry.getInstrumentation().getContext().getAssets().openFd(filename); return assetFileDescriptor.getLength(); } catch (IOException e) { return -1; } finally { if (assetFileDescriptor != null) { try { assetFileDescriptor.close(); } catch (IOException ignored) { } } } }
Example 8
Source File: ResourcePayload.java From cloudinary_android with MIT License | 6 votes |
@Override public long getLength(Context context) throws PayloadNotFoundException { AssetFileDescriptor afd = null; long size = 0; try { afd = context.getResources().openRawResourceFd(data); size = afd.getLength(); } catch (Resources.NotFoundException e) { throw new ResourceNotFoundException(String.format("Resource id %d not found", data)); } finally { if (afd != null) { try { afd.close(); } catch (IOException ignored) { } } } return size; }
Example 9
Source File: ApkAssets.java From cronet with BSD 3-Clause "New" or "Revised" License | 5 votes |
@CalledByNative public static long[] open(String fileName) { AssetFileDescriptor afd = null; try { AssetManager manager = ContextUtils.getApplicationContext().getAssets(); afd = manager.openNonAssetFd(fileName); return new long[] {afd.getParcelFileDescriptor().detachFd(), afd.getStartOffset(), afd.getLength()}; } catch (IOException e) { // As a general rule there's no point logging here because the caller should handle // receiving an fd of -1 sensibly, and the log message is either mirrored later, or // unwanted (in the case where a missing file is expected), or wanted but will be // ignored, as most non-fatal logs are. // It makes sense to log here when the file exists, but is unable to be opened as an fd // because (for example) it is unexpectedly compressed in an apk. In that case, the log // message might save someone some time working out what has gone wrong. // For that reason, we only suppress the message when the exception message doesn't look // informative (Android framework passes the filename as the message on actual file not // found, and the empty string also wouldn't give any useful information for debugging). if (!e.getMessage().equals("") && !e.getMessage().equals(fileName)) { Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e); } return new long[] {-1, -1, -1}; } finally { try { if (afd != null) { afd.close(); } } catch (IOException e2) { Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2); } } }
Example 10
Source File: DrawableDataSource.java From sketch with Apache License 2.0 | 5 votes |
@Override public long getLength() throws IOException { if (length >= 0) { return length; } AssetFileDescriptor fileDescriptor = null; try { fileDescriptor = context.getResources().openRawResourceFd(drawableId); length = fileDescriptor != null ? fileDescriptor.getLength() : 0; } finally { SketchUtils.close(fileDescriptor); } return length; }
Example 11
Source File: ApkAssets.java From 365browser with Apache License 2.0 | 5 votes |
@CalledByNative public static long[] open(String fileName) { AssetFileDescriptor afd = null; try { AssetManager manager = ContextUtils.getApplicationContext().getAssets(); afd = manager.openNonAssetFd(fileName); return new long[] {afd.getParcelFileDescriptor().detachFd(), afd.getStartOffset(), afd.getLength()}; } catch (IOException e) { // As a general rule there's no point logging here because the caller should handle // receiving an fd of -1 sensibly, and the log message is either mirrored later, or // unwanted (in the case where a missing file is expected), or wanted but will be // ignored, as most non-fatal logs are. // It makes sense to log here when the file exists, but is unable to be opened as an fd // because (for example) it is unexpectedly compressed in an apk. In that case, the log // message might save someone some time working out what has gone wrong. // For that reason, we only suppress the message when the exception message doesn't look // informative (Android framework passes the filename as the message on actual file not // found, and the empty string also wouldn't give any useful information for debugging). if (!e.getMessage().equals("") && !e.getMessage().equals(fileName)) { Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e); } return new long[] {-1, -1, -1}; } finally { try { if (afd != null) { afd.close(); } } catch (IOException e2) { Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2); } } }
Example 12
Source File: GifDrawable.java From Overchan-Android with GNU General Public License v3.0 | 5 votes |
/** * Creates drawable from AssetFileDescriptor. * Convenience wrapper for {@link GifDrawable#GifDrawable(FileDescriptor)} * * @param afd source * @throws NullPointerException if afd is null * @throws IOException when opening failed */ public GifDrawable(AssetFileDescriptor afd) throws IOException { if (afd == null) throw new NullPointerException("Source is null"); FileDescriptor fd = afd.getFileDescriptor(); try { mGifInfoPtr = openFd(mMetaData, fd, afd.getStartOffset(), false); } catch (IOException ex) { afd.close(); throw ex; } mColors = new int[mMetaData[0] * mMetaData[1]]; mInputSourceLength = afd.getLength(); }
Example 13
Source File: MockRequestHandler.java From u2020 with Apache License 2.0 | 5 votes |
@Override public Result load(Request request, int networkPolicy) throws IOException { String imagePath = request.uri.getPath().substring(1); // Grab only the path sans leading slash. // Check the disk cache for the image. A non-null return value indicates a hit. boolean cacheHit = emulatedDiskCache.get(imagePath) != null; // If there's a hit, grab the image stream and return it. if (cacheHit) { return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.DISK); } // If we are not allowed to hit the network and the cache missed return a big fat nothing. if (NetworkPolicy.isOfflineOnly(networkPolicy)) { return null; } // If we got this far there was a cache miss and hitting the network is required. See if we need // to fake an network error. if (behavior.calculateIsFailure()) { SystemClock.sleep(behavior.calculateDelay(MILLISECONDS)); throw new IOException("Fake network error!"); } // We aren't throwing a network error so fake a round trip delay. SystemClock.sleep(behavior.calculateDelay(MILLISECONDS)); // Since we cache missed put it in the LRU. AssetFileDescriptor fileDescriptor = assetManager.openFd(imagePath); long size = fileDescriptor.getLength(); fileDescriptor.close(); emulatedDiskCache.put(imagePath, size); // Grab the image stream and return it. return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.NETWORK); }
Example 14
Source File: FileUtil.java From GetApk with MIT License | 5 votes |
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 15
Source File: AssetsDataSource.java From sketch with Apache License 2.0 | 5 votes |
@Override public synchronized long getLength() throws IOException { if (length >= 0) { return length; } AssetFileDescriptor fileDescriptor = null; try { fileDescriptor = context.getAssets().openFd(assetsFilePath); length = fileDescriptor.getLength(); } finally { SketchUtils.close(fileDescriptor); } return length; }
Example 16
Source File: MockRequestHandler.java From u2020-mvp with Apache License 2.0 | 5 votes |
@Override public Result load(Request request, int networkPolicy) throws IOException { String imagePath = request.uri.getPath().substring(1); // Grab only the path sans leading slash. // Check the disk cache for the image. A non-null return value indicates a hit. boolean cacheHit = emulatedDiskCache.get(imagePath) != null; // If there's a hit, grab the image stream and return it. if (cacheHit) { return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.DISK); } // If we are not allowed to hit the network and the cache missed return a big fat nothing. if (NetworkPolicy.isOfflineOnly(networkPolicy)) { return null; } // If we got this far there was a cache miss and hitting the network is required. See if we need // to fake an network error. if (behavior.calculateIsFailure()) { SystemClock.sleep(behavior.calculateDelay(MILLISECONDS)); throw new IOException("Fake network error!"); } // We aren't throwing a network error so fake a round trip delay. SystemClock.sleep(behavior.calculateDelay(MILLISECONDS)); // Since we cache missed put it in the LRU. AssetFileDescriptor fileDescriptor = assetManager.openFd(imagePath); long size = fileDescriptor.getLength(); fileDescriptor.close(); emulatedDiskCache.put(imagePath, size); // Grab the image stream and return it. return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.NETWORK); }
Example 17
Source File: ContentDataSource.java From sketch with Apache License 2.0 | 5 votes |
@Override public synchronized long getLength() throws IOException { if (length >= 0) { return length; } AssetFileDescriptor fileDescriptor = null; try { fileDescriptor = context.getContentResolver().openAssetFileDescriptor(contentUri, "r"); length = fileDescriptor != null ? fileDescriptor.getLength() : 0; } finally { SketchUtils.close(fileDescriptor); } return length; }
Example 18
Source File: MediaUtil.java From appinventor-extensions with Apache License 2.0 | 4 votes |
/** * Loads the audio or video specified by mediaPath into the given * MediaPlayer. * * @param mediaPlayer the MediaPlayer * @param form the Form * @param mediaPath the path to the media */ public static void loadMediaPlayer(MediaPlayer mediaPlayer, Form form, String mediaPath) throws IOException { MediaSource mediaSource = determineMediaSource(form, mediaPath); switch (mediaSource) { case ASSET: AssetFileDescriptor afd = getAssetsIgnoreCaseAfd(form,mediaPath); try { FileDescriptor fd = afd.getFileDescriptor(); long offset = afd.getStartOffset(); long length = afd.getLength(); mediaPlayer.setDataSource(fd, offset, length); } finally { afd.close(); } return; case REPL_ASSET: form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE); mediaPlayer.setDataSource(replAssetPath(mediaPath)); return; case SDCARD: form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE); mediaPlayer.setDataSource(mediaPath); return; case FILE_URL: if (isExternalFileUrl(mediaPath)) { form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE); } mediaPlayer.setDataSource(fileUrlToFilePath(mediaPath)); return; case URL: // This works both for streaming and non-streaming. // TODO(halabelson): Think about whether we could get improved // performance if we did buffering control. mediaPlayer.setDataSource(mediaPath); return; case CONTENT_URI: mediaPlayer.setDataSource(form, Uri.parse(mediaPath)); return; case CONTACT_URI: throw new IOException("Unable to load audio or video for contact " + mediaPath + "."); } throw new IOException("Unable to load audio or video " + mediaPath + "."); }
Example 19
Source File: CheapAMR.java From MusicPlayer with GNU General Public License v3.0 | 4 votes |
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 20
Source File: ContentDataSource.java From MediaSDK with Apache License 2.0 | 4 votes |
@Override public long open(DataSpec dataSpec) throws ContentDataSourceException { try { Uri uri = dataSpec.uri; this.uri = uri; transferInitializing(dataSpec); AssetFileDescriptor assetFileDescriptor = resolver.openAssetFileDescriptor(uri, "r"); this.assetFileDescriptor = assetFileDescriptor; if (assetFileDescriptor == null) { throw new FileNotFoundException("Could not open file descriptor for: " + uri); } FileInputStream inputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor()); this.inputStream = inputStream; long assetStartOffset = assetFileDescriptor.getStartOffset(); long skipped = inputStream.skip(assetStartOffset + dataSpec.position) - assetStartOffset; if (skipped != dataSpec.position) { // We expect the skip to be satisfied in full. If it isn't then we're probably trying to // skip beyond the end of the data. throw new EOFException(); } if (dataSpec.length != C.LENGTH_UNSET) { bytesRemaining = dataSpec.length; } else { long assetFileDescriptorLength = assetFileDescriptor.getLength(); if (assetFileDescriptorLength == AssetFileDescriptor.UNKNOWN_LENGTH) { // The asset must extend to the end of the file. If FileInputStream.getChannel().size() // returns 0 then the remaining length cannot be determined. FileChannel channel = inputStream.getChannel(); long channelSize = channel.size(); bytesRemaining = channelSize == 0 ? C.LENGTH_UNSET : channelSize - channel.position(); } else { bytesRemaining = assetFileDescriptorLength - skipped; } } } catch (IOException e) { throw new ContentDataSourceException(e); } opened = true; transferStarted(dataSpec); return bytesRemaining; }