Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android系統教程 >> Android開發教程 >> Android加載SD卡目錄,文件夾遍歷,圖片設立,設置文件對應打開方式等

Android加載SD卡目錄,文件夾遍歷,圖片設立,設置文件對應打開方式等

編輯:Android開發教程

Android加載SD卡目錄,文件夾遍歷,圖片設置,設置文件對應打開方式等

此案例主要說的是Android使用GridView加載SD卡下所有目錄,文件夾多層遍歷,文件圖標修改,設置文件對應打開方式等功能。

如圖:

   

代碼:

 

public class GridViewFile extends Activity implements View.OnClickListener {

	private Context context;
	private TextView tv_title, textView;
	private GridView listView;
	private final String MUSIC_PATH = "/";

	// 記錄當前路徑下 的所有文件的數組
	File currentParent;
	// 記錄當前路徑下的所有文件的文件數組
	File[] currentFiles;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		initView();
	}

	public void initView() {
		findViewById(R.id.public_top_img_close).setOnClickListener(this);
		listView = (GridView) findViewById(R.id.gridview);
		textView = (TextView) findViewById(R.id.llss);
		onLoad();
	}

	public void onLoad() {
		ListSongsName();

	}

	private void ListSongsName() {

		// 獲取系統的SD卡目錄
		File root = new File(MUSIC_PATH);
		// 如果SD卡存在
		if (root.exists()) {
			currentParent = root;
			currentFiles = root.listFiles();// 獲取root目錄下的所有文件
			// 使用當前陸慕下的全部文件,文件夾來填充ListView
			inflateListView(currentFiles);
		}
		// 為ListView的列表項的單擊事件綁定監視器
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 用戶點擊了文件,則調用手機已安裝軟件操作該文件
				if (currentFiles[position].isFile()) {
					onError(currentFiles[position].getPath() + "1");
					Intent intent = OpenFile.openFile(currentFiles[position]
							.getPath());
					startActivity(intent);
				} else {

					// 獲取currentFiles[position]路徑下的所有文件
					File[] tmp = currentFiles[position].listFiles();
					if (tmp == null || tmp.length == 0) {
						Toast.makeText(GridViewFile.this, "空文件夾!",
								Toast.LENGTH_SHORT).show();
					}// if
					else {
						// 獲取用戶單擊的列表項對應的文件夾,設為當前的父文件夾
						currentParent = currentFiles[position];
						// 保存當前文件夾內的全部問價和文件夾
						currentFiles = tmp;
						inflateListView(currentFiles);
					}
				}
			}
		});

	}

	// 更新列表
	private void inflateListView(File[] files) {
		if (files.length == 0)
			Toast.makeText(GridViewFile.this, "sd卡不存在", Toast.LENGTH_SHORT)
					.show();
		else {
			// 創建一個List集合,List集合的元素是Map
			List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> listItem = new HashMap<String, Object>();
				// 如果當前File是文件夾,使用folder圖標;否則使用file圖標
				Log.i("path", files[i].getPath());
				Log.i("path", files[i].getName());
				if (files[i].isDirectory())
					listItem.put("icon", R.drawable.file_wenjianjia);
				// else if(files[i].isFi)
				else
					listItem.put("icon", R.drawable.file_wenjian1);
				listItem.put("fileName", files[i].getName());
				// 添加List項
				listItems.add(listItem);
			}
			// 創建一個SimpleAdapter
			SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
					R.layout.acheshi_item, new String[] { "icon", "fileName" },
					new int[] { R.id.imageView1, R.id.text_path });
			// 位ListView設置Adpter
			listView.setAdapter(simpleAdapter);
			try {
				textView.setText("當前路徑為:" + currentParent.getCanonicalPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onClick(View v) {
		onbey();
	}

	// 返回上層菜單
	private void onbey() {
		try {
			if (!MUSIC_PATH.equals(currentParent.getCanonicalPath())) {
				// 獲取上一層目錄
				currentParent = currentParent.getParentFile();
				// 列出當前目錄下的所有文件
				currentFiles = currentParent.listFiles();
				// 再次更新ListView
				inflateListView(currentFiles);
			} else {
				new AlertDialog.Builder(this)
						.setIcon(R.drawable.ic_launcher)
						.setTitle("提示")
						.setMessage("確定要退出嗎?")
						.setPositiveButton("確定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										finish();
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).create().show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onError(Object error) {
		Toast.makeText(getApplicationContext(), error + "", Toast.LENGTH_LONG)
				.show();
	}

	protected void onDestroy() {
		super.onDestroy();
	}

}

 

/**
 * 根據路徑調用系統對應的應用打開文件
 */

public class OpenFile {

    public static Intent openFile(String filePath){

        File file = new File(filePath);
        if(!file.exists()) return null;
            /* 取得擴展名 */
        String end=file.getName().substring(file.getName().lastIndexOf(".") + 1,file.getName().length()).toLowerCase();
            /* 依擴展名的類型決定MimeType */
        if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
                end.equals("xmf")||end.equals("ogg")||end.equals("wav")){
            return getAudioFileIntent(filePath);
        }else if(end.equals("3gp")||end.equals("mp4")){
            return getAudioFileIntent(filePath);
        }else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
                end.equals("jpeg")||end.equals("bmp")){
            return getImageFileIntent(filePath);
        }else if(end.equals("apk")){
            return getApkFileIntent(filePath);
        }else if(end.equals("ppt")){
            return getPptFileIntent(filePath);
        }else if(end.equals("xls")){
            return getExcelFileIntent(filePath);
        }else if(end.equals("doc")){
            return getWordFileIntent(filePath);
        }else if(end.equals("pdf")){
            return getPdfFileIntent(filePath);
        }else if(end.equals("chm")){
            return getChmFileIntent(filePath);
        }else if(end.equals("txt")){
            return getTextFileIntent(filePath,false);
        }else{
            return getAllIntent(filePath);
        }
    }

    //Android獲取一個用於打開APK文件的intent
    public static Intent getAllIntent( String param ) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);//動作
        Uri uri = Uri.fromFile(new File(param ));//轉換類型
        intent.setDataAndType(uri,"*/*");
        return intent;
    }
    //Android獲取一個用於打開APK文件的intent
    public static Intent getApkFileIntent( String param ) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri,"application/vnd.android.package-archive");
        return intent;
    }

    //Android獲取一個用於打開VIDEO文件的intent
    public static Intent getVideoFileIntent( String param ) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "video/*");
        return intent;
    }

    //Android獲取一個用於打開AUDIO文件的intent
    public static Intent getAudioFileIntent( String param ){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "audio/*");
        return intent;
    }

    //Android獲取一個用於打開Html文件的intent
    public static Intent getHtmlFileIntent( String param ){

        Uri uri = Uri.parse(param ).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param ).build();
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setDataAndType(uri, "text/html");
        return intent;
    }

    //Android獲取一個用於打開圖片文件的intent
    public static Intent getImageFileIntent( String param ) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "image/*");
        return intent;
    }

    //Android獲取一個用於打開PPT文件的intent
    public static Intent getPptFileIntent( String param ){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        return intent;
    }

    //Android獲取一個用於打開Excel文件的intent
    public static Intent getExcelFileIntent( String param ){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "application/vnd.ms-excel");
        return intent;
    }

    //Android獲取一個用於打開Word文件的intent
    public static Intent getWordFileIntent( String param ){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "application/msword");
        return intent;
    }

    //Android獲取一個用於打開CHM文件的intent
    public static Intent getChmFileIntent( String param ){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "application/x-chm");
        return intent;
    }

    //Android獲取一個用於打開文本文件的intent
    public static Intent getTextFileIntent( String param, boolean paramBoolean){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (paramBoolean){
            Uri uri1 = Uri.parse(param );
            intent.setDataAndType(uri1, "text/plain");
        }else{
            Uri uri2 = Uri.fromFile(new File(param ));
            intent.setDataAndType(uri2, "text/plain");
        }
        return intent;
    }
    //Android獲取一個用於打開PDF文件的intent
    public static Intent getPdfFileIntent( String param ){

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param ));
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }
}

 

不要忘記在AndroidManifest.xml加權限哦!

 <!-- SD卡權限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

 

源碼點擊下載

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved