自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

透過FileProvider再看ContentProvider

移動開發(fā) Android
大家應該都熟悉FileProvider吧,但是其誕生的原因,內部怎么實現(xiàn)的,又是怎么轉化為文件的,大家有了解多少呢?今天就通過它重新看看ContentProvider這個四大組件之一。

[[384130]]

前言

大家應該都熟悉FileProvider吧,但是其誕生的原因,內部怎么實現(xiàn)的,又是怎么轉化為文件的,大家有了解多少呢?今天就通過它重新看看ContentProvider這個四大組件之一。

在Android7.0,Android提高了應用的隱私權,限制了在應用間共享文件。如果需要在應用間共享,需要授予要訪問的URI臨時訪問權限。

以下是官方說明:

對于面向 Android 7.0 的應用,Android 框架執(zhí)行的 StrictMode API 政策禁止在您的應用外部公開 file:// URI。如果一項包含文件 URI 的 intent 離開您的應用,則應用出現(xiàn)故障,并出現(xiàn) FileUriExposedException 異常。要在應用間共享文件,您應發(fā)送一項 content:// URI,并授予 URI 臨時訪問權限。進行此授權的最簡單方式是使用 FileProvider 類。”

為什么限制在應用間共享文件

打個比方,應用A有一個文件,絕對路徑為file:///storage/emulated/0/Download/photo.jpg

現(xiàn)在應用A想通過其他應用來完成一些需求,比如拍照,就把他的這個文件路徑發(fā)給了照相應用B,然后應用B照完相就把照片存儲到了這個絕對路徑。

看起來似乎沒有什么問題,但是如果這個應用B是個“壞應用”呢?

  • 泄漏了文件路徑,也就是應用隱私。

如果這個應用A是“壞應用”呢?

  • 自己可以不用申請存儲權限,利用應用B就達到了存儲文件的這一危險權限。

可以看到,這個之前落伍的方案,從自身到對方,都是不太好的選擇。

所以Google就想了一個辦法,把對文件的訪問限制在應用內部。

  • 如果要分享文件路徑,不要分享file:// URI這種文件的絕對路徑,而是分享content:// URI,這種相對路徑,也就是這種格式:content://com.jimu.test.fileprovider/external/photo.jpg
  • 然后其他應用可以通過這個絕對路徑來向文件所屬應用 索要 文件數(shù)據,所以文件所屬的應用本身必須擁有文件的訪問權限。

也就是應用A分享相對路徑給應用B,應用B拿著這個相對路徑找到應用A,應用A讀取文件內容返給應用B。

配置FileProvider

搞清楚了要做什么事,接下來就是怎么做。

涉及到應用間通信的問題,還記得IPC的幾種方式嗎?

  • 文件
  • AIDL
  • ContentProvider
  • Socket
  • 等等。

從易用性,安全性,完整度等各個方面考慮,Google選擇了ContentProvider為這次限制應用分享文件的 解決方案。于是,F(xiàn)ileProvider誕生了。

具體做法就是:

  1. <!-- 配置FileProvider--> 
  2.  
  3. <provider 
  4.     android:name="androidx.core.content.FileProvider" 
  5.     android:authorities="${applicationId}.provider" 
  6.     android:exported="false" 
  7.     android:grantUriPermissions="true"
  8.     <meta-data 
  9.         android:name="android.support.FILE_PROVIDER_PATHS" 
  10.         android:resource="@xml/provider_paths"/> 
  11. </provider> 
  12.  
  13.  
  14.  
  15. <?xml version="1.0" encoding="utf-8"?> 
  16. <paths xmlns:android="http://schemas.android.com/apk/res/android"
  17.     <external-path name="external" path="."/> 
  18. </paths> 
  1. //修改文件URL獲取方式 
  2.  
  3. Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile()); 

這樣配置之后,就能生成content:// URI,并且也能通過這個URI來傳輸文件內容給外部應用。

FileProvider這些配置屬性也就是ContentProvider的通用配置:

  • android:name,是ContentProvider的類路徑。
  • android:authorities,是唯一標示,一般為包名+.provider
  • android:exported,表示該組件是否能被其他應用使用。
  • android:grantUriPermissions,表示是否允許授權文件的臨時訪問權限。

其中要注意的是android:exported正常應該是true,因為要給外部應用使用。

但是FileProvider這里設置為false,并且必須為false。

這主要為了保護應用隱私,如果設置為true,那么任何一個應用都可以來訪問當前應用的FileProvider了,對于應用文件來說不是很可取,所以Android7.0以上會通過其他方式讓外部應用安全的訪問到這個文件,而不是普通的ContentProvider訪問方式,后面會說到。

也正是因為這個屬性為true,在Android7.0以下,Android默認是將它當成一個普通的ContentProvider,外部無法通過content:// URI來訪問文件。所以一般要判斷下系統(tǒng)版本再確定傳入的Uri到底是File格式還是content格式。

FileProvider源碼

接著看看FileProvider的主要源碼:

  1. public class FileProvider extends ContentProvider { 
  2.  
  3.     @Override 
  4.     public boolean onCreate() { 
  5.         return true
  6.     } 
  7.  
  8.     @Override 
  9.     public void attachInfo(@NonNull Context context, @NonNull ProviderInfo info) { 
  10.         super.attachInfo(context, info); 
  11.  
  12.         // Sanity check our security 
  13.         if (info.exported) { 
  14.             throw new SecurityException("Provider must not be exported"); 
  15.         } 
  16.         if (!info.grantUriPermissions) { 
  17.             throw new SecurityException("Provider must grant uri permissions"); 
  18.         } 
  19.  
  20.         mStrategy = getPathStrategy(context, info.authority); 
  21.     } 
  22.  
  23.  
  24.     public static Uri getUriForFile(@NonNull Context context, @NonNull String authority, 
  25.             @NonNull File file) { 
  26.         final PathStrategy strategy = getPathStrategy(context, authority); 
  27.         return strategy.getUriForFile(file); 
  28.     } 
  29.  
  30.  
  31.     @Override 
  32.     public Uri insert(@NonNull Uri uri, ContentValues values) { 
  33.         throw new UnsupportedOperationException("No external inserts"); 
  34.     } 
  35.  
  36.  
  37.     @Override 
  38.     public int update(@NonNull Uri uri, ContentValues values, @Nullable String selection, 
  39.             @Nullable String[] selectionArgs) { 
  40.         throw new UnsupportedOperationException("No external updates"); 
  41.     } 
  42.  
  43.  
  44.     @Override 
  45.     public int delete(@NonNull Uri uri, @Nullable String selection, 
  46.             @Nullable String[] selectionArgs) { 
  47.         // ContentProvider has already checked granted permissions 
  48.         final File file = mStrategy.getFileForUri(uri); 
  49.         return file.delete() ? 1 : 0; 
  50.     } 
  51.  
  52.     @Override 
  53.     public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, 
  54.             @Nullable String[] selectionArgs, 
  55.             @Nullable String sortOrder) { 
  56.         // ContentProvider has already checked granted permissions 
  57.         final File file = mStrategy.getFileForUri(uri); 
  58.  
  59.         if (projection == null) { 
  60.             projection = COLUMNS; 
  61.         } 
  62.  
  63.         String[] cols = new String[projection.length]; 
  64.         Object[] values = new Object[projection.length]; 
  65.         int i = 0; 
  66.         for (String col : projection) { 
  67.             if (OpenableColumns.DISPLAY_NAME.equals(col)) { 
  68.                 cols[i] = OpenableColumns.DISPLAY_NAME; 
  69.                 values[i++] = file.getName(); 
  70.             } else if (OpenableColumns.SIZE.equals(col)) { 
  71.                 cols[i] = OpenableColumns.SIZE
  72.                 values[i++] = file.length(); 
  73.             } 
  74.         } 
  75.  
  76.         cols = copyOf(cols, i); 
  77.         values = copyOf(values, i); 
  78.  
  79.         final MatrixCursor cursor = new MatrixCursor(cols, 1); 
  80.         cursor.addRow(values); 
  81.         return cursor
  82.     } 
  83.  
  84.     @Override 
  85.     public String getType(@NonNull Uri uri) { 
  86.   final File file = mStrategy.getFileForUri(uri); 
  87.  
  88.         final int lastDot = file.getName().lastIndexOf('.'); 
  89.         if (lastDot >= 0) { 
  90.             final String extension = file.getName().substring(lastDot + 1); 
  91.             final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); 
  92.             if (mime != null) { 
  93.                 return mime; 
  94.             } 
  95.         } 
  96.         return "application/octet-stream"
  97.     } 
  98.  
  99.  

任何一個ContentProvider都需要繼承ContentProvider類,然后實現(xiàn)這幾個抽象方法:

onCreate,getType,query,insert,delete,update。

(其中每個方法中的Uri參數(shù),就是我們之前通過getUriForFile方法生成的content URI)

我們分三部分說說:

數(shù)據調用方面

其中,query,insert,delete,update四個方法就是數(shù)據的增刪查改,也就是進程間通信的相關方法。

其他應用可以通過ContentProvider來調用這幾個方法,來完成對本地應用數(shù)據的增刪查改,從而完成進程間通信的功能。

具體方法就是調用getContentResolver()的相關方法,例如:

  1. Cursor cursor = getContentResolver().query(uri, nullnullnull"userid");  

再回去看看FileProvider:

  • query,查詢方法。在該方法中,返回了File的name和length。
  • insert,插入方法。沒有做任何事。
  • delete,刪除方法。刪除Uri對應的File。
  • update,更新方法。沒有做任何事。

MIME類型

再看getType方法,這個方法主要是返回 Url所代表數(shù)據的MIME類型。

一般是使用默認格式:

  • 如果是單條記錄返回以vnd.android.cursor.item/ 為首的字符串
  • 如果是多條記錄返回vnd.android.cursor.dir/ 為首的字符串

具體怎么用呢?可以通過Content URI對應的ContentProvider配置的getType來匹配Activity。

有點拗口,比如Activity和ContentProvider這么配置的:

  1. <activity   
  2.     android:name=".SecondActivity">   
  3.     <intent-filter>   
  4.         <action android:name=""/>   
  5.         <category android:name=""/>   
  6.         <data android:mimeType="type_test"/>  
  7.     </intent-filter>   
  8. </activity>   
  1. @Override 
  2. public String getType(@NonNull Uri uri) { 
  3.     return "type_test"
  4.  
  5.  
  6. intent.setData(mContentRUI);   
  7. startActivity(intent) 

這樣配置之后,startActivity就會檢查Activity的mineType 和 Content URI 對應的ContentProvider的getType是否相同,相同情況下才能正常打開Activity。

初始化

最后再看看onCreate方法。

在APP啟動流程中,自動執(zhí)行所有ContentProvider的attachInfo方法,并最后調用到onCreate方法。一般在這個方法中就做一些初始化工作,比如初始化ContentProvider所需要的數(shù)據庫。

而在FileProvider中,調用了attachInfo方法作為了一個初始化工作的入口,其實和onCreate方法的作用一樣,都是App啟動的時候會調用的方法。

在這個方法中,也是限制了exported屬性必須為false,grantUriPermissions屬性必須為true。

  1. if (info.exported) { 
  2.     throw new SecurityException("Provider must not be exported"); 
  3. if (!info.grantUriPermissions) { 
  4.     throw new SecurityException("Provider must grant uri permissions"); 

這個初始化方法和特性,也是被很多三方庫所利用,可以進行靜默無感知的初始化工作,而無需單獨調用三方庫初始化方法。比如Facebook SDK:

  1. <provider 
  2.     android:name="com.facebook.internal.FacebookInitProvider" 
  3.     android:authorities="${applicationId}.FacebookInitProvider" 
  4.     android:exported="false" /> 
  1. public final class FacebookInitProvider extends ContentProvider { 
  2.     private static final String TAG = FacebookInitProvider.class.getSimpleName(); 
  3.  
  4.     @Override 
  5.     @SuppressWarnings("deprecation"
  6.     public boolean onCreate() { 
  7.         try { 
  8.             FacebookSdk.sdkInitialize(getContext()); 
  9.         } catch (Exception ex) { 
  10.             Log.i(TAG, "Failed to auto initialize the Facebook SDK", ex); 
  11.         } 
  12.         return false
  13.     } 
  14.  
  15.     //... 

這樣一寫,就無需單獨集成FacebookSDK的初始化方法了,實現(xiàn)靜默初始化。

而Jetpack中的App Startup也是考慮到這些三方庫的需求,對三方庫的初始化進行了一個合并,從而優(yōu)化了多次創(chuàng)建ContentProvider的耗時。

拿到Content URI 該怎么使用?

很多人都知道該怎么配置FileProvider讓別人(比如照相APP)來獲取我們的Content URI,但是你們知道別人拿到Content URI之后又是怎么獲取具體的File的呢?

其實仔細找找就能發(fā)現(xiàn),在FileProvider.java中有注釋說明:

  1. The client app that receives the content URI can open the file and access its contents by calling 
  2.  {@link android.content.ContentResolver#openFileDescriptor(Uri, String) ContentResolver.openFileDescriptor}  
  3.  to get a {@link ParcelFileDescriptor} 

也就是openFileDescriptor方法,拿到ParcelFileDescriptor類型數(shù)據,其實就是一個文件描述符,然后就可以讀取文件流了。

  1. ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(intent.getData(), "r"); 
  2. FileReader reader = new FileReader(parcelFileDescriptor.getFileDescriptor()); 
  3. BufferedReader bufferedReader = new BufferedReader(reader); 

ContentProvider 實際應用

在平時的工作中,主要有以下以下幾種情況和ContentProvider打交道比較多:

  • 和系統(tǒng)的一些App通信,比如獲取通訊錄,調用拍照等。上述的FileProvider也是屬于這種情況。
  • 與自己的APP有一些交互。比如自家多應用之間,可以通過這個進行一些數(shù)據交互。
  • 三方庫的初始化工作。很多三方庫會利用ContentProvider自動初始化這一特性,進行一個靜默無感知的初始化工作。

總結

ContentProvider作為四大組件之一,似乎并沒有其他組件的存在感那么強。

但是他還是有自己的那一份職責,也就是在保證安全的情況下進行應用間通信,還可以擴展作為幫助初始化的組件。所以了解他,掌握它也是很重要的,沒準以后哪個時候你就需要他了。

不要忽視任何一個知識點。

參考

https://mp.weixin.qq.com/s/kQmH2GnwW8FK-yNmWcheTA 

https://segmentfault.com/a/1190000021357383

https://blog.csdn.net/lmj623565791/article/details/72859156

本文轉載自微信公眾號「碼上積木」,可以通過以下二維碼關注。轉載本文請聯(lián)系碼上積木公眾號。

 

責任編輯:武曉燕 來源: 碼上積木
相關推薦

2014-07-29 15:57:01

ContentProv

2012-05-01 21:32:39

蘋果

2023-11-07 11:17:25

Android數(shù)據共享

2021-01-18 07:31:52

MySQL LeetCode查詢

2009-12-18 11:22:34

Ruby source

2013-11-13 10:33:10

KitKatAndroidChromeOS

2009-07-16 08:50:53

微軟未來操作系統(tǒng)Windows 7

2012-07-31 11:06:48

WebGL

2015-03-26 18:52:38

2015-12-21 11:11:26

2021-08-02 13:05:49

瀏覽器HTTP前端

2013-09-25 09:26:03

平臺軟件企業(yè)虛擬化云網絡

2023-02-17 18:32:42

JavaAIOIO

2010-04-23 10:41:21

鏈路負載均衡

2010-08-26 14:40:55

隱私保護

2012-07-12 15:27:46

WebGL

2016-03-18 13:02:19

2019-07-16 11:06:09

TCP四次揮手半關閉

2023-10-23 19:58:01

Android

2017-07-18 16:14:06

FileProvideAndroidStrictMode
點贊
收藏

51CTO技術棧公眾號