如果你的安卓程序的targetSdkVersion是24以上,也就是7.0。你需要使用FileProvider向其他應(yīng)用提供文件,而不是隨便地利用文件地址就可以。也就是說你需要使用 content:// 來代替file://。接下來提供步驟:
- 你最好提供自己的FileProvider擴展,而不是直接使用android.support.v4.content.FileProvider,以防止與其他app和庫沖突。
public class MyFileProvider extends FileProvider {
}
- 接下來,在AndroidManifest.xml中,添加一個provider標(biāo)簽
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name=".MyFileProvider"
android:authorities="${applicationId}.my.package.name.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
</manifest>
- 你應(yīng)該注意到,其中有一個xml資源,沒錯,你需要定義一個xml文件來說明你需要提供的文件路徑
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
在這個例子中,我們指出需要獲取外部儲存的根路徑,用.表示。
- 最后,你就可以獲取文件Uri了,注意,你需要
FLAG_GRANT_READ_URI_PERMISSION權(quán)限來完成這個工作。比如在intent中,獲取uri地址來安裝apk:
Intent intent= new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", apkfile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
startActivity(intent);