編集:この回答を修正して、最初に「特殊なContentProviderを書く」と呼んだアプローチのコード例を含めました。これは、質問の要件を完全に満たす必要があります。おそらく答えが大きくなりすぎますが、現在は内部コードの依存関係があるため、そのままにしておきましょう。主なポイントは依然として当てはまります。必要に応じて以下の ContentPrvder を使用しますがfile://
、誰かのアプリのクラッシュで非難されたくない場合を除き、それらをサポートするアプリに Uris を与えるようにしてください。
元の答え
今のように Storage Access Framework には近づかないでしょう。Google によるサポートが不十分であり、アプリでのサポートはひどいものであり、これらのアプリのバグと SAF 自体の見分けがつきにくくなっています。十分な自信がある場合 (これは、「平均的な Android 開発者よりも try-catch ブロックをうまく使用できる」ことを意味します)、自分で Storage Access Framework を使用しますが、他の人には古き良きfile://
パスのみを渡します。
次のトリックを使用して、 ParcelFileDescriptor からファイルシステム パスを取得できます ( openFileDescriptorを呼び出して ContentResolver から取得できます)。
class FdCompat {
public static String getFdPath(ParcelFileDescriptor fd) {
final String resolved;
try {
final File procfsFdFile = new File("/proc/self/fd/" + fd.getFd());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Returned name may be empty or "pipe:", "socket:", "(deleted)" etc.
resolved = Os.readlink(procfsFdFile.getAbsolutePath());
} else {
// Returned name is usually valid or empty, but may start from
// funny prefix if the file does not have a name
resolved = procfsFdFile.getCanonicalPath();
}
if (TextUtils.isEmpty(resolved) || resolved.charAt(0) != '/'
|| resolved.startsWith("/proc/") || resolved.startsWith("/fd/"))
return null;
} catch (IOException ioe) {
// This exception means, that given file DID have some name, but it is
// too long, some of symlinks in the path were broken or, most
// likely, one of it's directories is inaccessible for reading.
// Either way, it is almost certainly not a pipe.
return "";
} catch (Exception errnoe) {
// Actually ErrnoException, but base type avoids VerifyError on old versions
// This exception should be VERY rare and means, that the descriptor
// was made unavailable by some Unix magic.
return null;
}
return resolved;
}
}
上記のメソッドが null (ファイルは完全に正当なパイプまたはソケット) または空のパス (ファイルの親ディレクトリへの読み取りアクセスなし) を返すことを覚悟しておく必要があります。これが発生した場合は、ストリーム全体をアクセス可能なディレクトリにコピーします。
完全なソリューション
本当にコンテンツ プロバイダーの Uris を使い続けたい場合は、こちらをご覧ください。以下の ContentProvider のコードを見てください。アプリに貼り付けます (そして AndroidManifest に登録します)。以下のメソッドを使用getShareableUri
して、受け取った Storage Access Framework Uri を独自のものに変換します。元の URI の代わりに、その URI を他のアプリに渡します。
以下のコードは安全ではありません (簡単に安全にすることができますが、それを説明すると、この回答の長さが想像以上に長くなります)。気にする場合は、file://
Uris を使用してください。Linux ファイル システムは十分に安全であると広く考えられています。
以下のソリューションを拡張して、対応する Uri なしで任意のファイル記述子を提供することは、読者の演習として残されています。
public class FdProvider extends ContentProvider {
private static final String ORIGINAL_URI = "o";
private static final String FD = "fd";
private static final String PATH = "p";
private static final Uri BASE_URI =
Uri.parse("content://com.example.fdhelper/");
// Create an Uri from some other Uri and (optionally) corresponding
// file descriptor (if you don't plan to close it until your process is dead).
public static Uri getShareableUri(@Nullable ParcelFileDescriptor fd,
Uri trueUri) {
String path = fd == null ? null : FdCompat.getFdPath(fd);
String uri = trueUri.toString();
Uri.Builder builder = BASE_URI.buildUpon();
if (!TextUtils.isEmpty(uri))
builder.appendQueryParameter(ORIGINAL_URI, uri);
if (fd != null && !TextUtils.isEmpty(path))
builder.appendQueryParameter(FD, String.valueOf(fd.getFd()))
.appendQueryParameter(PATH, path);
return builder.build();
}
public boolean onCreate() { return true; }
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
String o = uri.getQueryParameter(ORIGINAL_URI);
String fd = uri.getQueryParameter(FD);
String path = uri.getQueryParameter(PATH);
if (TextUtils.isEmpty(o)) return null;
// offer the descriptor directly, if our process still has it
try {
if (!TextUtils.isEmpty(fd) && !TextUtils.isEmpty(path)) {
int intFd = Integer.parseInt(fd);
ParcelFileDescriptor desc = ParcelFileDescriptor.fromFd(intFd);
if (intFd >= 0 && path.equals(FdCompat.getFdPath(desc))) {
return desc;
}
}
} catch (RuntimeException | IOException ignore) {}
// otherwise just forward the call
try {
Uri trueUri = Uri.parse(o);
return getContext().getContentResolver()
.openFileDescriptor(trueUri, mode);
}
catch (RuntimeException ignore) {}
throw new FileNotFoundException();
}
// all other calls are forwarded the same way as above
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String o = uri.getQueryParameter(ORIGINAL_URI);
if (TextUtils.isEmpty(o)) return null;
try {
Uri trueUri = Uri.parse(o);
return getContext().getContentResolver().query(trueUri, projection,
selection, selectionArgs, sortOrder);
} catch (RuntimeException ignore) {}
return null;
}
public String getType(Uri uri) {
String o = uri.getQueryParameter(ORIGINAL_URI);
if (TextUtils.isEmpty(o)) return "*/*";
try {
Uri trueUri = Uri.parse(o);
return getContext().getContentResolver().getType(trueUri);
} catch (RuntimeException e) { return null; }
}
public Uri insert(Uri uri, ContentValues values) {
return null;
}
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) { return 0; }
}