android.content.res.AssetFileDescriptor#close()源码实例Demo

下面列出了android.content.res.AssetFileDescriptor#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: fresco   文件: LocalAssetFetchProducer.java
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.
    }
  }
}
 
源代码2 项目: fresco   文件: LocalResourceFetchProducer.java
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.
    }
  }
}
 
源代码3 项目: AndroidUtilCode   文件: FileUtils.java
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;
}
 
源代码4 项目: openboard   文件: BinaryDictionaryGetter.java
/**
 * 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) {
        }
    }
}
 
源代码5 项目: SchoolQuest   文件: Game.java
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);
        }
    });
}
 
源代码6 项目: jmonkeyengine   文件: NativeVorbisLoader.java
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();
        }
    }
}
 
源代码7 项目: moVirt   文件: BeepManager.java
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;
    }
}
 
源代码8 项目: QRScanner   文件: BeepManager.java
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;
    }
}
 
源代码9 项目: Study_Android_Demo   文件: BeepManager.java
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.
    }
  }
}
 
源代码12 项目: Indic-Keyboard   文件: BinaryDictionaryGetter.java
/**
 * 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) {
        }
    }
}
 
源代码13 项目: xDrip-plus   文件: AlertPlayer.java
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;
}
 
源代码14 项目: FireFiles   文件: IoUtils.java
/**
 * 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) {
        }
    }
}
 
源代码15 项目: u2020-mvp   文件: MockRequestHandler.java
@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);
    }
}
 
源代码17 项目: Overchan-Android   文件: GifDrawable.java
/**
 * 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());
        }
    }
}
 
源代码19 项目: FireFiles   文件: IoUtils.java
/**
 * 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) {
        }
    }
}
 
源代码20 项目: 365browser   文件: ApkAssets.java
@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);
        }
    }
}