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

The following examples show how to use android.content.res.AssetFileDescriptor#close() . 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: BeepManager.java    From moVirt with Apache License 2.0 7 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 2
Source File: LocalAssetFetchProducer.java    From fresco with MIT License 6 votes vote down vote up
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 3
Source File: BinaryDictionaryGetter.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a file address from a resource, or null if it cannot be opened.
 */
public static AssetFileAddress loadFallbackResource(final Context context,
        final int fallbackResId) {
    AssetFileDescriptor afd = null;
    try {
        afd = context.getResources().openRawResourceFd(fallbackResId);
    } catch (RuntimeException e) {
        Log.e(TAG, "Resource not found: " + fallbackResId);
        return null;
    }
    if (afd == null) {
        Log.e(TAG, "Resource cannot be opened: " + fallbackResId);
        return null;
    }
    try {
        return AssetFileAddress.makeFromFileNameAndOffset(
                context.getApplicationInfo().sourceDir, afd.getStartOffset(), afd.getLength());
    } finally {
        try {
            afd.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 4
Source File: LocalAssetFetchProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected 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 5
Source File: LocalResourceFetchProducer.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
@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 6
Source File: BeepManager.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  try {
    AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
    try {
      mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    } finally {
      file.close();
    }
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setLooping(false);
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
    return mediaPlayer;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer.release();
    return null;
  }
}
 
Example 7
Source File: BeepManager.java    From QRScanner with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 8
Source File: NativeVorbisLoader.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 9
Source File: Game.java    From SchoolQuest with GNU General Public License v3.0 6 votes vote down vote up
public void playJingle(int jingleId) {
    jingle.reset();

    bgm.setVolume(0, 0);

    AssetFileDescriptor afd = GameActivity.getInstance().getResources().
            openRawResourceFd(jingleId);
    if (afd == null) return;

    try {
        jingle.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        jingle.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    jingle.start();

    jingle.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            bgm.setVolume(1, 1);
        }
    });
}
 
Example 10
Source File: BinaryDictionaryGetter.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a file address from a resource, or null if it cannot be opened.
 */
public static AssetFileAddress loadFallbackResource(final Context context,
        final int fallbackResId) {
    AssetFileDescriptor afd = null;
    try {
        afd = context.getResources().openRawResourceFd(fallbackResId);
    } catch (RuntimeException e) {
        Log.e(TAG, "Resource not found: " + fallbackResId);
        return null;
    }
    if (afd == null) {
        Log.e(TAG, "Resource cannot be opened: " + fallbackResId);
        return null;
    }
    try {
        return AssetFileAddress.makeFromFileNameAndOffset(
                context.getApplicationInfo().sourceDir, afd.getStartOffset(), afd.getLength());
    } finally {
        try {
            afd.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 11
Source File: FileUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
private static boolean isFileExistsApi29(String filePath) {
    if (Build.VERSION.SDK_INT >= 29) {
        try {
            Uri uri = Uri.parse(filePath);
            ContentResolver cr = Utils.getApp().getContentResolver();
            AssetFileDescriptor afd = cr.openAssetFileDescriptor(uri, "r");
            if (afd == null) return false;
            try {
                afd.close();
            } catch (IOException ignore) {
            }
        } catch (FileNotFoundException e) {
            return false;
        }
        return true;
    }
    return false;
}
 
Example 12
Source File: LocalResourceFetchProducer.java    From fresco with MIT License 6 votes vote down vote up
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 13
Source File: GifDrawable.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 14
Source File: OpenSLMediaPlayer.java    From android-openslmediaplayer with Apache License 2.0 5 votes vote down vote up
static void closeQuietly(AssetFileDescriptor afd) {
    if (afd != null) {
        try {
            afd.close();
        } catch (IOException e) {
            Log.w(TAG, "closeQuietly() " + e.getStackTrace());
        }
    }
}
 
Example 15
Source File: BinaryDictionaryFileDumper.java    From Indic-Keyboard with Apache License 2.0 5 votes vote down vote up
private static void closeAssetFileDescriptorAndReportAnyException(
        final AssetFileDescriptor file) {
    try {
        if (null != file) file.close();
    } catch (Exception e) {
        Log.e(TAG, "Exception while closing a file", e);
    }
}
 
Example 16
Source File: IoUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Closes 'AssetFileDescriptor', ignoring any checked exceptions. Does nothing if 'AssetFileDescriptor' is null.
 */
public static void closeQuietly(AssetFileDescriptor closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (RuntimeException rethrown) {
            throw rethrown;
        } catch (Exception ignored) {
        }
    }
}
 
Example 17
Source File: MockRequestHandler.java    From u2020-mvp with Apache License 2.0 5 votes vote down vote up
@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 18
Source File: IoUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Closes 'AssetFileDescriptor', ignoring any checked exceptions. Does nothing if 'AssetFileDescriptor' is null.
 */
public static void closeQuietly(AssetFileDescriptor closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (RuntimeException rethrown) {
            throw rethrown;
        } catch (Exception ignored) {
        }
    }
}
 
Example 19
Source File: ApkAssets.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@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 20
Source File: AlertPlayer.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private boolean setMediaDataSource(Context context, MediaPlayer mp, int resid) {
    try {
        AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
        if (afd == null) return false;

        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();

        return true;
    } catch (IOException | NullPointerException | IllegalArgumentException | SecurityException ex) {
        Log.e(TAG, "setMediaDataSource from resource id failed:", ex);
    }
    return false;
}