FileProvide 快速使用

google建議未來要使用手機內部儲存的空間都要先問使用者。


if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)

{ActivityCompat.requestPermissions(this,

new String[{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE_ASK_WRITE_EXTERNAL_STORAGE_PERMISSIONS);}



這樣就會出現詢問是否讓app使用儲存空間。



接下來用FileProvider,快速使用法

1.在res/xml/建一個file_paths.xml的檔案,內容如下。這個檔的作用就是,當我們要得到Uri的路徑時,images這個資料匣名稱(參考下方的XML檔),就會用my_images來替代。以我們的例子,Uri就會變成
content://comp.example.test/my_images/default_image.jpeg



<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
    <files-path name="my_docs" path="docs/"/>
</paths>


2.AndroidManifest.xml中


<application>


    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="comp.example.test"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>


</application>



3.程式的使用


File imagePath = new File(Context.getFilesDir(), "images");

if (!imagePath.exists()) imagePath.mkdir();

File newFile = new File(imagePath, "default_image.jpg");

Uri contentUri = getUriForFile(getContext(), "comp.example.test", newFile);

留言

這個網誌中的熱門文章

python 找圖自動點擊

Python pyserial 抓取系統內的 COM PORT

VBA EXCEL 工作表變化 馬上執行 的作法 Worksheet_Change