使用FileProvider共享文件

最近学习FileProvider,不知为何,汉语资料很少。所以就自己啃官方文档,实现了一遍。
官方文档路径:
http://developer.android.com/intl/zh-cn/training/secure-file-sharing/setup-sharing.html
需要一下几步
一、在共享端设置

首先,需要在 Menifest里添加 provider 标签,

        
            
        



然后,指定共享目录
     在res目录下,新建目录xml,在xml下新建filepaths.xml 文件


    
      
      
    

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

二、创建一个文件选择Activity。
        
        
            
                

                
                

                
                
            
        


三、在代码中响应

       
/*当条目被点击时,设置setResult,将选择的结果返回给调用此activity的activity*/
       @Override
       public boolean onChildClick (ExpandableListView parent, View v,
                   int groupPosition, int childPosition, long id) {
            /*得到点击的File*/
            File file = ((File[])mGroupMap.get(mGroups [groupPosition]))[childPosition];
            Uri fileUri;
            /*authority 必须和Menifest的provider标签里定义的一致*/
            String authority = getResources().getString(R.string.fileprovider_authority );
             try {
                 fileUri = FileProvider. getUriForFile(
                    FileSelectActivity. this,
                    authority,
                    file);
            Intent resultIntent = new Intent();
            if (fileUri != null) {
                  resultIntent.addFlags(
                         Intent. FLAG_GRANT_READ_URI_PERMISSION );
                // Put the Uri and MIME type in the result Intent
                  resultIntent.setDataAndType(
                        fileUri,
                        getContentResolver().getType(fileUri));
                // 设置返回结果状态,
                  setResult(Activity. RESULT_OK,
                              resultIntent);
            } else {
                  resultIntent.setDataAndType( null, "" );
                  setResult( RESULT_CANCELED,
                              resultIntent);
            }                        
            finish();                      
        } catch (Exception e) {
            e.printStackTrace();                         
        }
             finally{
                  finish();
            }
             return true ;
      }


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


     被调用Activity返回前,调用setResult方法,设置了 RESULT_OK,在被调用Activity结束后,系统会调用 onActivityResult方法
          得到之前设置的RESULT_OK状态,表示成功获取到文件。如果获取失败,则应该设置RESULT_CANCEL。
             @Override
             public void onActivityResult(int requestCode, int resultCode,
                        Intent data) {
                   // TODO Auto-generated method stub
                   if (resultCode != RESULT_OK) {
                         tvFileContent.setText("未成功获得文件" );
                         tvFileName.setText("未成功获得文件" );
                  } else {
                        readFile(data.getData());
                  }
            }
            
             private void readFile(Uri returnUri) {
                  Context context = getActivity();
                  ParcelFileDescriptor inputPFD;
                   //获取文件句柄
                   try {                
                        inputPFD = context.getContentResolver().openFileDescriptor(returnUri, "r" );
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                tvFileContent.setText("获取文件句柄失败" );
                tvFileName.setText("获取文件句柄失败" );
                return;
            }
                  
                   //获取文件名字和大小
                   Cursor returnCursor =
                        context.getContentResolver().query(returnUri, null, null , null, null);
                /*
                 * Get the column indexes of the data in the Cursor,
                 * move to the first row in the Cursor, get the data,
                 * and display it.
                 */
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                returnCursor.moveToFirst();
                tvFileName.setText("文件名:" +returnCursor.getString(nameIndex)+", 大小:"+
                Long. toString(returnCursor.getLong(sizeIndex))+" B");
                  returnCursor.close();
                  
                   //读取文件内容
                  String content = "";
                  FileReader fr = null;
                   char[] buffer = new char[1024];
                  
                   try {
                        StringBuilder strBuilder = new StringBuilder();
                        fr = new FileReader(inputPFD.getFileDescriptor());
                         while (fr.read(buffer) != -1) {
                              strBuilder.append(buffer);
                        }
                        fr.close();
                        content = strBuilder.toString();
                  } catch (Exception e) {
                         // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
                  
                   if (content.length() != 0) {
                         tvFileContent.setText(content);
                  } else {
                         tvFileContent.setText("<内容空>" );
                  }
                  
                   try {
                        inputPFD.close();
                  } catch (IOException e) {
                         // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
            }
      }

代码下载

你可能感兴趣的:(android,android,FileProvider)