直接调用文件管理器选择即可。
1、调用系统提供的选择器,代码如下:
//注意,在Android44系统下建议使用 IntentACTION_OPEN_DOCUMENT方式
if (UtilityisKK()) {
Intent intent = new Intent(IntentACTION_OPEN_DOCUMENT);
intentaddCategory(IntentCATEGORY_OPENABLE);
intentsetType("image
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
处理返回结果:
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
superonActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PIC_RESULT://选择图库
case PIC_RESULT_KK:
imageFileUri = intentgetData();//获取选择的URI
break;
}
}
2、除此自外,系统还提供一种选择器,这个选择器可以屏蔽掉那个auto backup的目录所以就开始打算用这个选择器来选了
Intent intent=new Intent(IntentACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
intentaddCategory(IntentCATEGORY_OPENABLE);
intentsetType("image/jpeg");
if(androidosBuildVERSIONSDK_INT>=androidosBuildVERSION_CODESKITKAT){
startActivityForResult(intent, SELECT_PIC_KITKAT);
}else{
startActivityForResult(intent, SELECT_PIC);
}
为什么要分开不同版本呢其实在43或以下可以直接用ACTION_GET_CONTENT的,在44或以上,官方建议用ACTION_OPEN_DOCUMENT,主要区别是他们返回的Uri43返回的是带文件路径的,而44返回的却是content://comandroidprovidersmediadocuments/document/image:3951这样的,没有路径,只有编号的uri可以通过以下方式,处理URI。
参考:Android 44从图库选择,获取路径并裁剪
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = BuildVERSIONSDK_INT >= BuildVERSION_CODESKITKAT;
// DocumentProvider
if (isKitKat && DocumentsContractisDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContractgetDocumentId(uri);
final String[] split = docIdsplit(":");
final String type = split[0];
if ("primary"equalsIgnoreCase(type)) {
return EnvironmentgetExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContractgetDocumentId(uri);
final Uri contentUri = ContentUriswithAppendedId(
Uriparse("content://downloads/public_downloads"), LongvalueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContractgetDocumentId(uri);
final String[] split = docIdsplit(":");
final String type = split[0];
Uri contentUri = null;
if ("image"equals(type)) {
contentUri = MediaStoreImagesMediaEXTERNAL_CONTENT_URI;
} else if ("video"equals(type)) {
contentUri = MediaStoreVideoMediaEXTERNAL_CONTENT_URI;
} else if ("audio"equals(type)) {
contentUri = MediaStoreAudioMediaEXTERNAL_CONTENT_URI;
}
final String selection = "_id=";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content"equalsIgnoreCase(urigetScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return urigetLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file"equalsIgnoreCase(urigetScheme())) {
return urigetPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = contextgetContentResolver()query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursormoveToFirst()) {
final int index = cursorgetColumnIndexOrThrow(column);
return cursorgetString(index);
}
} finally {
if (cursor != null)
cursorclose();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "comandroidexternalstoragedocuments"equals(urigetAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "comandroidprovidersdownloadsdocuments"equals(urigetAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "comandroidprovidersmediadocuments"equals(urigetAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "comgoogleandroidappsphotoscontent"equals(urigetAuthority());
}
3、使用其它开源组件如PhotoView。
package comexamples_27;
import javaioFile;
import androidappActivity;
import androidosBundle;
public class MainActivity extends Activity {
public static int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
superonCreate(savedInstanceState);
setContentView(Rlayoutactivity_main);
new Thread() {
public void run() {
String path = "/sdcard/androidesk/";
getFiles(path);
Systemoutprintln(path + " 文件夹下面共有 " + i + " 张文件");
};
}start();
}
private void getFiles(String string) {
// TODO Auto-generated method stub
File file = new File(string);
File[] files = filelistFiles();
for (int j = 0; j < fileslength; j++) {
String name = files[j]getName();
if (files[j]isDirectory()) {
String dirPath = files[j]toString()toLowerCase();
Systemoutprintln(dirPath);
getFiles(dirPath + "/");
} else if (files[j]isFile() & nameendsWith("jpg") || nameendsWith("png") || nameendsWith("bmp") || nameendsWith("gif") || nameendsWith("jpeg")) {
Systemoutprintln("FileName===" + files[j]getName());
i++;
}
}
}
}
清单文件 manifest 节点下面添加 读取权限
<uses-permission android:name="androidpermissionREAD_EXTERNAL_STORAGE" />有的时候程序需要去对android的指定目录或者全局目录进行遍历获取其中的文件,但是获取文件的时候可能会遇到无法列出文件夹中的文件的问题,这就是出现的问题,对于某个子文件夹进行获取listFiles()的时候返回为NULL,也就是不允许列出文件夹中内容。
这个是由于android中的安全机制的缘故,由于android继承了Linux系统的传统,对于某个特定的目录有用户的权限,一共分为三种--可读,可写,可执行;虽然说可以设置某个特定的目录的权限,但是对于目录里面的子目录和子文件都可以进行权限的设置,也就是说出了根目录权限之外,子目录本身的权限也决定了子目录可否访问,这一点需要清楚了解,所以在判断完了是否是目录之外,还需要在进行listFiles()获取File[]数据后判断获取的数组是否为空,如果为空的话,文件夹是不可访问的。样例代码如下:
01 package netnowamagicfile;
02 import javaioFile;
03 import javautilArrayList;
04 import javautilHashMap;
05 import javautilMap;
06 import androidutilLog;
07 /
08 @author
09 function 用于扫描SD卡上的文件
10
11 /
12 public class FileScan {
13
14 private static final String TAG = "FileScan";
15 public HashMap<String, String> getMusicListOnSys(File file) {
16
17 //从根目录开始扫描
18 Logi(TAG, filegetPath());
19 HashMap<String, String> fileList = new HashMap<String, String>();
20 getFileList(file, fileList);
21 return fileList;
22 }
23
24 /
25 @param path
26 @param fileList
27 注意的是并不是所有的文件夹都可以进行读取的,权限问题
28 /
29 private void getFileList(File path, HashMap<String, String> fileList){
30 //如果是文件夹的话
31 if(pathisDirectory()){
32 //返回文件夹中有的数据
33 File[] files = pathlistFiles();
34 //先判断下有没有权限,如果没有权限的话,就不执行了
35 if(null == files)
36 return;
37
38 for(int i = 0; i < fileslength; i++){
39 getFileList(files[i], fileList);
40 }
41 }
42 //如果是文件的话直接加入
43 else{
44 Logi(TAG, pathgetAbsolutePath());
45 //进行文件的处理
46 String filePath = pathgetAbsolutePath();
47 //文件名
48 String fileName = filePathsubstring(filePathlastIndexOf("/")+1);
49 //添加
50 fileListput(fileName, filePath);
51 }
52 }
53
54 }
出处:>
通过主动的方式通知系统我们需要文件列表,要向系统发送广播
sendBroadcast(new Intent(IntentACTION_MEDIA_MOUNTED, Uriparse(“file://”+ EnvironmentgetExternalStorageDirectory())));
然后通过接收器获取系统文列表
public class MediaScannerReceiver extends BroadcastReceiver{
private final static String TAG = ”MediaScannerReceiver”;
@Override
public void onReceive(Context context, Intent intent) {
String action = intentgetAction();
Uri uri = intentgetData();
String externalStoragePath = EnvironmentgetExternalStorageDirectory()getPath();
if (actionequals(IntentACTION_BOOT_COMPLETED)) {
// scan internal storage
scan(context, MediaProviderINTERNAL_VOLUME);
} else {
if (urigetScheme()equals(“file”)) {
// handle intents related to external storage
String path = urigetPath();
if (actionequals(IntentACTION_MEDIA_MOUNTED) &&
externalStoragePathequals(path)) {
scan(context, MediaProviderEXTERNAL_VOLUME);
} else if (actionequals(IntentACTION_MEDIA_SCANNER_SCAN_FILE) &&
path != null && pathstartsWith(externalStoragePath + ”/”)) {
scanFile(context, path);
}
}
}
}
private void scan(Context context, String volume) {
Bundle args = new Bundle();
argsputString(“volume”, volume);
contextstartService(
new Intent(context, MediaScannerServiceclass)putExtras(args));
}
private void scanFile(Context context, String path) {
Bundle args = new Bundle();
argsputString(“filepath”, path);
contextstartService(
new Intent(context, MediaScannerServiceclass)putExtras(args));
}
}
如果想读取StreamingAssets文件夹下的资源直接使用ApplicationstreamingAssetsPath这个就可以了。
注意:此路径只可以读取,不能写入哟。
我写了个例子,你看能用吗
package comdragonredandroidutils;
import javaioBufferedWriter;
import javaioByteArrayOutputStream;
import javaioFile;
import javaioFileInputStream;
import javaioFileOutputStream;
import javaioIOException;
import javaioOutputStreamWriter;
import javaioRandomAccessFile;
import javatextSimpleDateFormat;
import javautilDate;
import androidcontentContext;
import androidcontentSharedPreferences;
import androidosEnvironment;
import androidutilLog;
public final class FileUtils {
public final static String PACKAGE_PATH = "comdragonredandroid";
// public final static String LOG_FILE_NAME = "smartprinttxt";
// public final static String LOG_FILE_PATH = STORE_DIRECTORY_PATH + FileseparatorChar + LOG_FILE_NAME;
/
read key value from preference by key name
@param context
@param keyName
@return
/
public final static String readPreperence(Context context, String keyName) {
SharedPreferences settings = contextgetSharedPreferences(
PACKAGE_PATH, 0);
return settingsgetString(keyName, "");
}
/
write key name and key value into preference
@param context
@param keyName
@param keyValue
/
public final static void writePreperence(Context context, String keyName,
String keyValue) {
SharedPreferences settings = contextgetSharedPreferences(
PACKAGE_PATH, 0);
SharedPreferencesEditor editor = settingsedit();
editorputString(keyName, keyValue);
editorcommit();
}
/
delete key from preference by key name
@param context
@param keyName
/
public final static void deletePreperence(Context context, String keyName) {
SharedPreferences settings = contextgetSharedPreferences(
PACKAGE_PATH, 0);
SharedPreferencesEditor editor = settingsedit();
editorremove(keyName);
editorcommit();
}
public final static String getContextFilePath(Context context, String fileName) {
return contextgetFilesDir()getAbsolutePath() + FileseparatorChar + fileName;
}
public final static boolean existContextFile(Context context, String fileName) {
String filePath = contextgetFilesDir()getAbsolutePath() + FileseparatorChar + fileName;
Logd("filePath", filePath);
File file = new File(filePath);
if (fileexists()) {
return true;
}
return false;
}
public final static void saveContextFile(Context context, String fileName, String content) throws Exception {
FileOutputStream outputStream = contextopenFileOutput(fileName, ContextMODE_PRIVATE);
outputStreamwrite(contentgetBytes());
outputStreamclose();
}
public final static void saveAppendContextFile(Context context, String fileName, String content) throws Exception {
FileOutputStream outputStream = contextopenFileOutput(fileName, ContextMODE_APPEND);
outputStreamwrite(contentgetBytes());
outputStreamclose();
}
public final static void deleteContextFile(Context context, String fileName) throws Exception {
contextdeleteFile(fileName);
}
public final static String readContextFile(Context context, String fileName) throws Exception {
FileInputStream inputStream = contextopenFileInput(fileName);
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = -1;
while ((len = inputStreamread(buffer)) != -1) {
byteArrayOutputStreamwrite(buffer, 0, len);
}
byte[] data = byteArrayOutputStreamtoByteArray();
byteArrayOutputStreamclose();
inputStreamclose();
return new String(data);
}
/
delete file or folders
@param file
/
public final static void deleteFile(File file) {
if (fileexists()) {
if (fileisFile()) {
filedelete();
} else if (fileisDirectory()) {
File files[] = filelistFiles();
for (int i = 0; i < fileslength; i++) {
deleteFile(files[i]);
}
}
filedelete();
} else {
Logd("deleteFile", "The file or directory does not exist!");
}
}
/
make directory on SD card
@param dirPath
@return
/
public final static boolean makeDir(String dirPath) {
File dir = new File(dirPath);
if(!dirisDirectory()) {
if (dirmkdirs()) {
return true;
}
} else {
return true;
}
return false;
}
/
write log file
@param filePath
@param tag
@param content
/
public final static void writeLog(String filePath, String tag, String content) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String logDateTime = sdfformat(new Date());
writeFileByAppend(filePath, logDateTime + "---[" + tag + "]---" + content + "\n");
}
/
write file by append mode
@param filePath
@param content
/
public final static void writeFileByAppend(String filePath, String content) {
// FileWriter writer = null;
// try {
// writer = new FileWriter(filePath, true);
// writerwrite(content);
// } catch (IOException e) {
// eprintStackTrace();
// } finally {
// try {
// writerclose();
// } catch (IOException e) {
// eprintStackTrace();
// }
// }
RandomAccessFile randomFile = null;
try {
randomFile = new RandomAccessFile(filePath, "rw");
long fileLength = randomFilelength();
randomFileseek(fileLength);
randomFilewrite(contentgetBytes());
} catch (IOException e) {
eprintStackTrace();
} finally {
try {
randomFileclose();
} catch (IOException e) {
eprintStackTrace();
}
}
// BufferedWriter out = null;
// try {
// out = new BufferedWriter(new OutputStreamWriter(
// new FileOutputStream(filePath, true), "UTF-8"));
// outwrite(content);
// } catch (Exception e) {
// eprintStackTrace();
// } finally {
// try {
// outclose();
// } catch (IOException e) {
// eprintStackTrace();
// }
// }
}
/
write file by overwrite mode
@param filePath
@param content
/
public final static void writeFile(String filePath, String content) {
// FileWriter writer = null;
// try {
// writer = new FileWriter(filePath, true);
// writerwrite(content);
// } catch (IOException e) {
// eprintStackTrace();
// } finally {
// try {
// writerclose();
// } catch (IOException e) {
// eprintStackTrace();
// }
// }
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath, false), "UTF-8"));
outwrite(content);
} catch (Exception e) {
eprintStackTrace();
} finally {
try {
outclose();
} catch (IOException e) {
eprintStackTrace();
}
}
}
/
check SD card whether or not exist
@param context
@return
/
public final static boolean checkSDCard(Context context) {
if (EnvironmentMEDIA_MOUNTEDequals(Environment
getExternalStorageState())) {
return true;
} else {
// ToastmakeText(context, "Please check your SD card! ",
// ToastLENGTH_SHORT)show();
return false;
}
}
/
read last line from file
@param filePath
@return
/
public final static String readLastLinefromFile(String filePath) {
RandomAccessFile raf = null;
try {
File file = new File(filePath);
if (!fileexists()) {
return null;
}
raf = new RandomAccessFile(filePath, "r");
long len = raflength();
if (len == 0L) {
return "";
} else {
long pos = len - 1;
while (pos > 0) {
pos--;
rafseek(pos);
if (rafreadByte() == '\n') {
break;
}
}
if (pos == 0) {
rafseek(0);
}
byte[] bytes = new byte[(int) (len - pos)];
rafread(bytes);
return new String(bytes);
}
} catch (Exception e) {
eprintStackTrace();
} finally {
if (raf != null) {
try {
rafclose();
} catch (Exception e2) {
}
}
}
return null;
}
}
以上就是关于android怎么从sd卡指定的文件夹中获取所有图片的路径URL,谢谢~感谢各位大神了全部的内容,包括:android怎么从sd卡指定的文件夹中获取所有图片的路径URL,谢谢~感谢各位大神了、安卓开发 如何获取sd卡中的某个文件夹的图片个数、android开发怎样获得文件夹中的所有文件等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)