使用FileProvider共享文件

 需要一下几步
一、在共享端设置

首先,需要在 Menifest里添加 provider 标签,
[html]  view plain  copy
  1. <!-- 在这里定义共享信息 -->  
  2.         <provider  
  3.             android:name="android.support.v4.content.FileProvider"  
  4.             android:authorities="com.example.fileproviderdemo.fileprovider"  
  5.             android:exported="false"  
  6.             android:grantUriPermissions="true" >  
  7.             <meta-data  
  8.                 android:name="android.support.FILE_PROVIDER_PATHS"  
  9.                 android:resource="@xml/filepaths" />  
  10.         </provider>  



然后,指定共享目录
     在res目录下,新建目录xml,在xml下新建filepaths.xml 文件
[html]  view plain  copy
  1. <?xml version="1.0" encoding"utf-8"?>  
  2. <resources>  
  3.     <paths >  
  4.       <files-path path="files/" name="intfiles" />  
  5.       <external-path path="files/" name="extfiles" />  
  6.     </paths >  
  7. </resources>  

     别忘了外部路径需要权限。

二、创建一个文件选择Activity。
[html]  view plain  copy
  1. <!-- 文件选择页面ACTIVITY -->  
  2. <activity  
  3.     android:name=".FileSelectActivity"  
  4.     android:label="@string/app_name" >  
  5.     <intent-filter>  
  6.         <action android:name="android.intent.action.PICK" />  
  7.   
  8.         <category android:name="android.intent.category.DEFAULT" />  
  9.         <category android:name="android.intent.category.OPENABLE" />  
  10.   
  11.         <data android:mimeType="text/plain" />  
  12.         <data android:mimeType="image/*" />  
  13.     </intent-filter>  
  14. </activity>  


三、在代码中响应

       
[java]  view plain  copy
  1. /*当条目被点击时,设置setResult,将选择的结果返回给调用此activity的activity*/  
  2.        @Override  
  3.        public boolean onChildClick (ExpandableListView parent, View v,  
  4.                    int groupPosition, int childPosition, long id) {  
  5.             /*得到点击的File*/  
  6.             File file = ((File[])mGroupMap.get(mGroups [groupPosition]))[childPosition];  
  7.             Uri fileUri;  
  8.             /*authority 必须和Menifest的provider标签里定义的一致*/  
  9.             String authority = getResources().getString(R.string.fileprovider_authority );  
  10.              try {  
  11.                  fileUri = FileProvider. getUriForFile(  
  12.                     FileSelectActivity. this,  
  13.                     authority,  
  14.                     file);  
  15.             Intent resultIntent = new Intent();  
  16.             if (fileUri != null) {  
  17.                   resultIntent.addFlags(  
  18.                          Intent. FLAG_GRANT_READ_URI_PERMISSION );  
  19.                 // Put the Uri and MIME type in the result Intent  
  20.                   resultIntent.setDataAndType(  
  21.                         fileUri,  
  22.                         getContentResolver().getType(fileUri));  
  23.                 // 设置返回结果状态,  
  24.                   setResult(Activity. RESULT_OK,  
  25.                               resultIntent);  
  26.             } else {  
  27.                   resultIntent.setDataAndType( null"" );  
  28.                   setResult( RESULT_CANCELED,  
  29.                               resultIntent);  
  30.             }                          
  31.             finish();                        
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();                           
  34.         }  
  35.              finally{  
  36.                   finish();  
  37.             }  
  38.              return true ;  
  39.       }  


四、在请求端,也就是请求共享的App的代码中,发起请求
[java]  view plain  copy
  1. Intent intent = new Intent(Intent.ACTION_PICK);  
  2.                  intent.setType( "text/plain");  
  3.                  startActivityForResult(intent, 0);  


     被调用Activity返回前,调用setResult方法,设置了 RESULT_OK,在被调用Activity结束后,系统会调用 onActivityResult方法
          得到之前设置的RESULT_OK状态,表示成功获取到文件。如果获取失败,则应该设置RESULT_CANCEL。
[java]  view plain  copy
  1.  @Override  
  2.  public void onActivityResult(int requestCode, int resultCode,  
  3.             Intent data) {  
  4.        // TODO Auto-generated method stub  
  5.        if (resultCode != RESULT_OK) {  
  6.              tvFileContent.setText("未成功获得文件" );  
  7.              tvFileName.setText("未成功获得文件" );  
  8.       } else {  
  9.             readFile(data.getData());  
  10.       }  
  11. }  
  12.   
  13.  private void readFile(Uri returnUri) {  
  14.       Context context = getActivity();  
  15.       ParcelFileDescriptor inputPFD;  
  16.        //获取文件句柄  
  17.        try {                  
  18.             inputPFD = context.getContentResolver().openFileDescriptor(returnUri, "r" );  
  19. catch (FileNotFoundException e) {  
  20.     e.printStackTrace();  
  21.     tvFileContent.setText("获取文件句柄失败" );  
  22.     tvFileName.setText("获取文件句柄失败" );  
  23.     return;  
  24. }  
  25.         
  26.        //获取文件名字和大小  
  27.        Cursor returnCursor =  
  28.             context.getContentResolver().query(returnUri, nullnull , nullnull);  
  29.     /* 
  30.      * Get the column indexes of the data in the Cursor, 
  31.      * move to the first row in the Cursor, get the data, 
  32.      * and display it. 
  33.      */  
  34.     int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);  
  35.     int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);  
  36.     returnCursor.moveToFirst();  
  37.     tvFileName.setText("文件名:" +returnCursor.getString(nameIndex)+", 大小:"+  
  38.     Long. toString(returnCursor.getLong(sizeIndex))+" B");  
  39.       returnCursor.close();  
  40.         
  41.        //读取文件内容  
  42.       String content = "";  
  43.       FileReader fr = null;  
  44.        char[] buffer = new char[1024];  
  45.         
  46.        try {  
  47.             StringBuilder strBuilder = new StringBuilder();  
  48.             fr = new FileReader(inputPFD.getFileDescriptor());  
  49.              while (fr.read(buffer) != -1) {  
  50.                   strBuilder.append(buffer);  
  51.             }  
  52.             fr.close();  
  53.             content = strBuilder.toString();  
  54.       } catch (Exception e) {  
  55.              // TODO Auto-generated catch block  
  56.             e.printStackTrace();  
  57.       }  
  58.         
  59.        if (content.length() != 0) {  
  60.              tvFileContent.setText(content);  
  61.       } else {  
  62.              tvFileContent.setText("<内容空>" );  
  63.       }  
  64.         
  65.        try {  
  66.             inputPFD.close();  
  67.       } catch (IOException e) {  
  68.              // TODO Auto-generated catch block  
  69.             e.printStackTrace();  
  70.       }  

猜你喜欢

转载自blog.csdn.net/xlwang9090/article/details/80843531
今日推荐