如何通过Content Provider的openFile()方法传播Exceptions? (API 14)

时间:2016-04-25 14:45:03

标签: android exception android-contentprovider

我正在使用

public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

如果我调用它并且CP无法提供该文件,则无论我在CP端执行什么操作,调用者(客户端)仍将获得空文件。也就是说,CP端文件提供程序(我在网络上检索文件)上的异常将永远不会传播到调用者,从而导致异常。这可以在API 14上解决吗?

代码看起来像这样:

ContentProvider:

@Override
public ParcelFileDescriptor openFile(Uri uri, String args) throws FileNotFoundException {
    try {
        return openPipeHelper(uri, "application/octet-stream", null, null, new FileDeliverer(uri, args)); //FileDeliverer constructor can cause MalformedURLException
    } catch (IOException e) {
        throw new FileNotFoundException("IOException when connecting!");
    }
}

FileDeliverer类(实现ContentProvider.PipeDataWriter)具有以下覆盖方法:

@Override
public void writeDataToPipe(ParcelFileDescriptor clientSideParcelFileDescriptor, Uri uri, String s, Bundle bundle, Object o) {
    InputStream inputStream;
    ParcelFileDescriptor.AutoCloseOutputStream autoCloseOutputStream=null;

    BasicHttpURLConnectorToTry basicHttpURLConnectorToTry =new BasicHttpURLConnectorToTry(url, timeOutMs);
    try {
        RepeatRetries repeatRetries = new RepeatRetries(basicHttpURLConnectorToTry, retries, retryDelayMs);
        inputStream = (InputStream) repeatRetries.executeWithRetries();
        autoCloseOutputStream=new ParcelFileDescriptor.AutoCloseOutputStream(clientSideParcelFileDescriptor);

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            autoCloseOutputStream.write(buffer, 0, len);
        }

    } catch (Exception e) {
        Log.e("FileDeliverer", "Exception when connecting or delivering data to client!", e);
    } finally {
        basicHttpURLConnectorToTry.closeStreamAndDisconnect();
        try {
            autoCloseOutputStream.close();
        } catch (Exception e) {
            Log.w("FileDeliverer", "Couldn't close OutputStream!", e);
        }

    }
}

0 个答案:

没有答案