Android通过ContentProvider传输文件


我们知道Android两个应用程序之间进行数据交互需要通过ContentProvider,而且通常都是数据库的操作。
今天项目需要使用Android的ContentProvider交互普通SD卡上的文件,于是我写了这个小例子:

AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.h3c.test"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="15" />  
  8.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  9.   
  10.     <application  
  11.         android:icon="@drawable/ic_launcher"  
  12.         android:label="@string/app_name" >  
  13.         <activity  
  14.             android:label="@string/app_name"  
  15.             android:name=".NotepadTestActivity" >  
  16.             <intent-filter >  
  17.                 <action android:name="android.intent.action.MAIN" />  
  18.   
  19.                 <category android:name="android.intent.category.LAUNCHER" />  
  20.             </intent-filter>  
  21.         </activity>  
  22.           
  23.         <provider android:name=".TestContentProvider" android:authorities="com.h3c.test" />  
  24.     </application>  
  25.   
  26. </manifest>  
TestContentProvider.java
  1. package com.h3c.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7.   
  8. import android.content.ContentProvider;  
  9. import android.content.ContentProviderOperation;  
  10. import android.content.ContentProviderResult;  
  11. import android.content.ContentValues;  
  12. import android.content.OperationApplicationException;  
  13. import android.content.res.AssetFileDescriptor;  
  14. import android.database.Cursor;  
  15. import android.net.Uri;  
  16. import android.os.Environment;  
  17. import android.os.ParcelFileDescriptor;  
  18. import android.util.Log;  
  19.   
  20. public class TestContentProvider extends ContentProvider {  
  21.   
  22.     @Override  
  23.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  24.         // TODO Auto-generated method stub   
  25.         Log.e("H3c""delete");  
  26.         return 0;  
  27.     }  
  28.   
  29.     @Override  
  30.     public String getType(Uri uri) {  
  31.         // TODO Auto-generated method stub   
  32.         Log.e("H3c""gettype");  
  33.         return null;  
  34.     }  
  35.   
  36.     @Override  
  37.     public Uri insert(Uri uri, ContentValues values) {  
  38.         // TODO Auto-generated method stub   
  39.         Log.e("H3c""insert");  
  40.         return null;  
  41.     }  
  42.   
  43.     @Override  
  44.     public boolean onCreate() {  
  45.         // TODO Auto-generated method stub   
  46.         Log.e("H3c""create");  
  47.         return false;  
  48.     }  
  49.   
  50.     @Override  
  51.     public Cursor query(Uri uri, String[] projection, String selection,  
  52.             String[] selectionArgs, String sortOrder) {  
  53.         // TODO Auto-generated method stub   
  54.         Log.e("H3c""query");  
  55.         return null;  
  56.     }  
  57.   
  58.     @Override  
  59.     public int update(Uri uri, ContentValues values, String selection,  
  60.             String[] selectionArgs) {  
  61.         // TODO Auto-generated method stub   
  62.         Log.e("H3c""update");  
  63.         return 0;  
  64.     }  
  65.   
  66.     @Override  
  67.     public AssetFileDescriptor openAssetFile(Uri uri, String mode)  
  68.             throws FileNotFoundException {  
  69.         // TODO Auto-generated method stub   
  70.         Log.e("H3c""openAssetFile");  
  71.         return super.openAssetFile(uri, mode);  
  72.     }  
  73.   
  74.     //此方法非常重要,一定要重写,否则默认报FileNotFound异常   
  75.     @Override  
  76.     public ParcelFileDescriptor openFile(Uri uri, String mode)  
  77.             throws FileNotFoundException {  
  78.         // TODO Auto-generated method stub   
  79.         File root = Environment.getExternalStorageDirectory();  
  80.         root.mkdirs();  
  81.         File path = new File(root, uri.getEncodedPath());  
  82.   
  83.         Log.e("H3c""opeFile:"+path);  
  84.         int imode = 0;  
  85.         if (mode.contains("w")) {  
  86.             imode |= ParcelFileDescriptor.MODE_WRITE_ONLY;  
  87.             if (!path.exists()) {  
  88.                 try {  
  89.                     path.createNewFile();  
  90.                 } catch (IOException e) {  
  91.                     e.printStackTrace();  
  92.                 }  
  93.             }  
  94.         }  
  95.         if (mode.contains("r"))  
  96.             imode |= ParcelFileDescriptor.MODE_READ_ONLY;  
  97.         if (mode.contains("+"))  
  98.             imode |= ParcelFileDescriptor.MODE_APPEND;  
  99.   
  100.         return ParcelFileDescriptor.open(path, imode);  
  101.     }  
  102.   
  103. }  
NotepadTestActivity.java
  1. package com.h3c.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.lang.reflect.InvocationTargetException;  
  11. import java.lang.reflect.Method;  
  12.   
  13. import android.app.Activity;  
  14. import android.content.Context;  
  15. import android.content.pm.PackageManager.NameNotFoundException;  
  16. import android.content.res.AssetFileDescriptor;  
  17. import android.net.Uri;  
  18. import android.os.Bundle;  
  19. import android.util.Log;  
  20. import android.view.View;  
  21. import android.view.View.OnClickListener;  
  22. import android.widget.Button;  
  23.   
  24. public class NotepadTestActivity extends Activity {  
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         // TODO Auto-generated method stub   
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.notepad);  
  30.   
  31.         Button button = (Button) findViewById(R.id.notepad);  
  32.         button.setOnClickListener(new OnClickListener() {  
  33.   
  34.             @Override  
  35.             public void onClick(View v) {  
  36.                 try {  
  37.                     // 直接读文件   
  38.                     // InputStream is = getContentResolver().openInputStream(   
  39.                     // Uri.parse("file:/mnt/sdcard/h3c.txt"));   
  40.                     //   
  41.                     // File bkFile = new File("/mnt/sdcard/h3c2.txt");   
  42.                     // if (!bkFile.exists()) {   
  43.                     // bkFile.createNewFile();   
  44.                     // }   
  45.                     //                       
  46.                     // FileOutputStream out = new FileOutputStream(bkFile);   
  47.                     // byte[] b = new byte[1024 * 5]; // 5KB   
  48.                     // int len;   
  49.                     // while ((len = is.read(b)) != -1) {   
  50.                     // out.write(b, 0, len);   
  51.                     // }   
  52.                     // out.flush();   
  53.                     // is.close();   
  54.                     // out.close();   
  55.   
  56.                     // 直接写文件   
  57.                     // OutputStream out = getContentResolver().openOutputStream(   
  58.                     // Uri.parse("file:/mnt/sdcard/h3c.txt"));   
  59.                     // FileInputStream in = new FileInputStream(new File(   
  60.                     // "/mnt/sdcard/h3c3.txt"));   
  61.                     //   
  62.                     // byte[] b = new byte[1024 * 5]; // 5KB   
  63.                     // int len;   
  64.                     // while ((len = in.read(b)) != -1) {   
  65.                     // out.write(b, 0, len);   
  66.                     // }   
  67.                     // out.flush();   
  68.                     //                       
  69.                     // in.close();   
  70.                     // out.close();   
  71.   
  72.                     // 内容流写   
  73.                     // AssetFileDescriptor afd = getContentResolver()   
  74.                     // .openAssetFileDescriptor(   
  75.                     // Uri.parse("content://com.h3c.test/h3c.txt"),   
  76.                     // "wr");   
  77.                     // InputStream in = afd.createInputStream();   
  78.                     // File bkFile = new File("/mnt/sdcard/h3c2.txt");   
  79.                     // if (!bkFile.exists()) {   
  80.                     // bkFile.createNewFile();   
  81.                     // }   
  82.                     //   
  83.                     // FileOutputStream out = new FileOutputStream(bkFile);   
  84.                     // byte[] b = new byte[1024 * 5]; // 5KB   
  85.                     // int len;   
  86.                     // while ((len = in.read(b)) != -1) {   
  87.                     // out.write(b, 0, len);   
  88.                     // }   
  89.                     // out.flush();   
  90.                     // in.close();   
  91.                     // out.close();   
  92.   
  93.                     // 内容流读   
  94.                     AssetFileDescriptor afd = getContentResolver()  
  95.                             .openAssetFileDescriptor(  
  96.                                     Uri.parse("content://com.h3c.test/h3c.txt"),  
  97.                                     "wr");  
  98.                     OutputStream out = afd.createOutputStream();  
  99.                     FileInputStream in = new FileInputStream(new File(  
  100.                             "/mnt/sdcard/h3c2.txt"));  
  101.   
  102.                     byte[] b = new byte[1024 * 5]; // 5KB   
  103.                     int len;  
  104.                     while ((len = in.read(b)) != -1) {  
  105.                         out.write(b, 0, len);  
  106.                     }  
  107.                     out.flush();  
  108.   
  109.                     in.close();  
  110.                     out.close();  
  111.                 } catch (FileNotFoundException e) {  
  112.                     e.printStackTrace();  
  113.                 } catch (IOException e) {  
  114.                     e.printStackTrace();  
  115.                 }  
  116.             }  
  117.         });  
  118.   
  119.     }  
  120. }  

相关内容