Android开发总结笔记 四大组件之ContentPovider(下) 1-2-9
2015-10-23 10:05
459 查看
Intentintent=newIntent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivity(intent);
从上图可以看出,Picker就是调用者和内容提供者的一个桥梁
咱们来试试获取一下UripublicclassMainActivityextendsAppCompatActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
privatevoidinit(){
Intentintent=newIntent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent,0x00);
}
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
if(requestCode==0x00&&resultCode==RESULT_OK){
if(null!=data){
Uriuri=data.getData();
Log.i("data",uri+"");
}
}
}
}
publicvoiddumpImageMetaData(Uriuri){
Cursorcursor=getContentResolver()
.query(uri,null,null,null,null,null);
try{
if(cursor!=null&&cursor.moveToFirst()){
StringdisplayName=cursor.getString(
cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.e("HeHe","DisplayName:"+displayName);
intsizeIndex=cursor.getColumnIndex(OpenableColumns.SIZE);
Stringsize=null;
if(!cursor.isNull(sizeIndex)){
size=cursor.getString(sizeIndex);
}else{
size="Unknown";
}
Log.e("HeHe","Size:"+size);
}
}finally{
cursor.close();
}
}根据Uri获取Bitmap
privateBitmapgetBitmapFromUri(Uriuri)throwsIOException{
ParcelFileDescriptorparcelFileDescriptor=
getContentResolver().openFileDescriptor(uri,"r");
FileDescriptorfileDescriptor=parcelFileDescriptor.getFileDescriptor();
Bitmapimage=BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
returnimage;
}根据Uri获取输入流
privateStringreadTextFromUri(Uriuri)throwsIOException{
InputStreaminputStream=getContentResolver().openInputStream(uri);
BufferedReaderreader=newBufferedReader(newInputStreamReader(
inputStream));
StringBuilderstringBuilder=newStringBuilder();
Stringline;
while((line=reader.readLine())!=null){
stringBuilder.append(line);
}
fileInputStream.close();
parcelFileDescriptor.close();
returnstringBuilder.toString();
}根据Uri创建新文件以及删除文件创建
privatevoidcreateFile(StringmimeType,StringfileName){
Intentintent=newIntent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_TITLE,fileName);
startActivityForResult(intent,WRITE_REQUEST_CODE);
}删除前提是Document.COLUMN_FLAGS包含SUPPORTS_DELETE
DocumentsContract.deleteDocument(getContentResolver(),uri);自定义DocumentProvider(API19以上)
<manifest...>
...
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19"/>
....
<provider
android:name="com.example.android.storageprovider.MyCloudProvider"
android:authorities="com.example.android.storageprovider.documents"
android:grantUriPermissions="true"
android:exported="true"
android:permission="android.permission.MANAGE_DOCUMENTS"
android:enabled="@bool/atLeastKitKat">
<intent-filter>
<actionandroid:name="android.content.action.DOCUMENTS_PROVIDER"/>
</intent-filter>
</provider>
</application>
</manifest>至少实现下面几个方法queryRoots()queryChildDocuments()queryDocument()openDocument()下面是一个访问文件的系统的DocumentProvider的大致写法
publicCursorqueryRoots(String[]projection)throwsFileNotFoundException{
//Createacursorwitheithertherequestedfields,orthedefault
//projectionif"projection"isnull.
finalMatrixCursorresult=
newMatrixCursor(resolveRootProjection(projection));
//Ifuserisnotloggedin,returnanemptyrootcursor.Thisremovesour
//providerfromthelistentirely.
if(!isUserLoggedIn()){
returnresult;
}
//It'spossibletohavemultipleroots(e.g.formultipleaccountsinthe
//sameapp)--justaddmultiplecursorrows.
//Constructonerowforarootcalled"MyCloud".
finalMatrixCursor.RowBuilderrow=result.newRow();
row.add(Root.COLUMN_ROOT_ID,ROOT);
row.add(Root.COLUMN_SUMMARY,getContext().getString(R.string.root_summary));
//FLAG_SUPPORTS_CREATEmeansatleastonedirectoryundertherootsupports
//creatingdocuments.FLAG_SUPPORTS_RECENTSmeansyourapplication'smost
//recentlyuseddocumentswillshowupinthe"Recents"category.
//FLAG_SUPPORTS_SEARCHallowsuserstosearchalldocumentstheapplication
//shares.
row.add(Root.COLUMN_FLAGS,Root.FLAG_SUPPORTS_CREATE|
Root.FLAG_SUPPORTS_RECENTS|
Root.FLAG_SUPPORTS_SEARCH);
//COLUMN_TITLEistheroottitle(e.g.Gallery,Drive).
row.add(Root.COLUMN_TITLE,getContext().getString(R.string.title));
//Thisdocumentidcannotchangeonceit'sshared.
row.add(Root.COLUMN_DOCUMENT_ID,getDocIdForFile(mBaseDir));
//ThechildMIMEtypesareusedtofiltertherootsandonlypresenttothe
//userrootsthatcontainthedesiredtypesomewhereintheirfilehierarchy.
row.add(Root.COLUMN_MIME_TYPES,getChildMimeTypes(mBaseDir));
row.add(Root.COLUMN_AVAILABLE_BYTES,mBaseDir.getFreeSpace());
row.add(Root.COLUMN_ICON,R.drawable.ic_launcher);
returnresult;
}
@Override
publicCursorqueryChildDocuments(StringparentDocumentId,String[]projection,
StringsortOrder)throwsFileNotFoundException{
finalMatrixCursorresult=new
MatrixCursor(resolveDocumentProjection(projection));
finalFileparent=getFileForDocId(parentDocumentId);
for(Filefile:parent.listFiles()){
//Addsthefile'sdisplayname,MIMEtype,size,andsoon.
includeFile(result,null,file);
}
returnresult;
}
@Override
publicCursorqueryDocument(StringdocumentId,String[]projection)throws
FileNotFoundException{
//Createacursorwiththerequestedprojection,orthedefaultprojection.
finalMatrixCursorresult=new
MatrixCursor(resolveDocumentProjection(projection));
includeFile(result,documentId,null);
returnresult;
}文档的内容基本上也就这些了。Android4.4获取资源路径的问题因为SAF的出现,所以4.4以上和以下的版本获取出来的Uri会变得不一样网上找的一套解决方案
publicstaticStringgetPath(finalContextcontext,finalUriuri){
finalbooleanisKitKat=Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT;
//DocumentProvider
if(isKitKat&&DocumentsContract.isDocumentUri(context,uri)){
//ExternalStorageProvider
if(isExternalStorageDocument(uri)){
finalStringdocId=DocumentsContract.getDocumentId(uri);
finalString[]split=docId.split(":");
finalStringtype=split[0];
if("primary".equalsIgnoreCase(type)){
returnEnvironment.getExternalStorageDirectory()+"/"+split[1];
}
//TODOhandlenon-primaryvolumes
}
//DownloadsProvider
elseif(isDownloadsDocument(uri)){
finalStringid=DocumentsContract.getDocumentId(uri);
finalUricontentUri=ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),Long.valueOf(id));
returngetDataColumn(context,contentUri,null,null);
}
//MediaProvider
elseif(isMediaDocument(uri)){
finalStringdocId=DocumentsContract.getDocumentId(uri);
finalString[]split=docId.split(":");
finalStringtype=split[0];
UricontentUri=null;
if("image".equals(type)){
contentUri=MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}elseif("video".equals(type)){
contentUri=MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}elseif("audio".equals(type)){
contentUri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
finalStringselection="_id=?";
finalString[]selectionArgs=newString[]{
split[1]
};
returngetDataColumn(context,contentUri,selection,selectionArgs);
}
}
//MediaStore(andgeneral)
elseif("content".equalsIgnoreCase(uri.getScheme())){
returngetDataColumn(context,uri,null,null);
}
//File
elseif("file".equalsIgnoreCase(uri.getScheme())){
returnuri.getPath();
}
returnnull;
}
/**
*GetthevalueofthedatacolumnforthisUri.Thisisusefulfor
*MediaStoreUris,andotherfile-basedContentProviders.
*
*@paramcontextThecontext.
*@paramuriTheUritoquery.
*@paramselection(Optional)Filterusedinthequery.
*@paramselectionArgs(Optional)Selectionargumentsusedinthequery.
*@returnThevalueofthe_datacolumn,whichistypicallyafilepath.
*/
publicstaticStringgetDataColumn(Contextcontext,Uriuri,Stringselection,
String[]selectionArgs){
Cursorcursor=null;
finalStringcolumn="_data";
finalString[]projection={
column
};
try{
cursor=context.getContentResolver().query(uri,projection,selection,selectionArgs,
null);
if(cursor!=null&&cursor.moveToFirst()){
finalintcolumn_index=cursor.getColumnIndexOrThrow(column);
returncursor.getString(column_index);
}
}finally{
if(cursor!=null)
cursor.close();
}
returnnull;
}
/**
*@paramuriTheUritocheck.
*@returnWhethertheUriauthorityisExternalStorageProvider.
*/
publicstaticbooleanisExternalStorageDocument(Uriuri){
return"com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
*@paramuriTheUritocheck.
*@returnWhethertheUriauthorityisDownloadsProvider.
*/
publicstaticbooleanisDownloadsDocument(Uriuri){
return"com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
*@paramuriTheUritocheck.
*@returnWhethertheUriauthorityisMediaProvider.
*/
publicstaticbooleanisMediaDocument(Uriuri){
return"com.android.providers.media.documents".equals(uri.getAuthority());
}
相关文章推荐
- 【Android应用开发】Android Studio 错误集锦 -- 将所有的 AS 错误集合到本文
- 【Android应用开发】Android Studio 错误集锦 -- 将所有的 AS 错误集合到本文
- android比较时间
- Android 线程池及多线程下载,Progressbar动态更新以及文件保存sd卡
- Android 线程池及多线程下载,Progressbar动态更新以及文件保存sd卡
- AndroidScreenSlide项目切换view动画效果《IT蓝豹》
- Android--Activity简介及生命周期
- AndroidVideoPlayer在线播放视频
- android 动画实现(一)Tween动画
- Android 三大图片缓存原理、特性对比
- Android API Level最新版本到6.0Platform Codenames, Versions, API Levels, and NDK Releases
- Android Fragment应用实战
- android ListViewA-Z字母索引
- android里面播放声音的方法---执行某项操作发出滴的一声
- android.content.ActivityNotFoundException: Unable to find explicit activity class have you declared this activity in your AndroidManifest.xml?
- Android Gradle实用技巧——APK文件名中加上SVN版本号,日期等
- Android -- Looper.prepare()和Looper.loop() —深入版
- Activity生命周期的自我理解
- Android:layout_gravity和android:gravity的区别
- Android ExpandableListView开发简介