下面列出了android.content.res.AssetFileDescriptor#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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.
}
}
}
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.
}
}
}
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;
}
/**
* 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) {
}
}
}
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);
}
});
}
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();
}
}
}
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;
}
}
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;
}
}
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;
}
}
@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.
}
}
}
@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.
}
}
}
/**
* 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) {
}
}
}
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;
}
/**
* 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) {
}
}
}
@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);
}
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);
}
}
/**
* 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();
}
static void closeQuietly(AssetFileDescriptor afd) {
if (afd != null) {
try {
afd.close();
} catch (IOException e) {
Log.w(TAG, "closeQuietly() " + e.getStackTrace());
}
}
}
/**
* 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) {
}
}
}
@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);
}
}
}