Android loads SD card directory, folder traversal, picture setting, setting file corresponding opening method, etc.

This case mainly talks about Android using GridView to load all directories under SD card, multi-layer traversal of folders, modification of file icons, and setting the corresponding opening method of files.

As shown in the figure:

   

Code:

 

public class GridViewFile extends Activity implements View.OnClickListener {

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

	// record an array of all files in the current path
	File currentParent;
	// Record the file array of all files under the current path
	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() {

		// Get the SD card directory of the system
		File root = new File(MUSIC_PATH);
		// if SD card exists
		if (root.exists()) {
			currentParent = root;
			currentFiles = root.listFiles();// Get all files in the root directory
			// Use all files and folders under the current Lu Mu to populate the ListView
			inflateListView(currentFiles);
		}
		// Bind the monitor for the click event of the ListView's list item
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// If the user clicks on the file, call the installed software on the phone to operate the file
				if (currentFiles[position].isFile()) {
					onError(currentFiles[position].getPath() + "1");
					Intent intent = OpenFile.openFile(currentFiles[position]
							.getPath());
					startActivity(intent);
				} else {

					// Get all files under the currentFiles[position] path
					File[] tmp = currentFiles[position].listFiles();
					if (tmp == null || tmp.length == 0) {
						Toast.makeText(GridViewFile.this, "Empty folder!",
								Toast.LENGTH_SHORT).show();
					}// if
					else {
						// Get the folder corresponding to the list item clicked by the user and set it as the current parent folder
						currentParent = currentFiles[position];
						// Save all asks and folders in the current folder
						currentFiles = tmp;
						inflateListView(currentFiles);
					}
				}
			}
		});

	}

	// update list
	private void inflateListView(File[] files) {
		if (files.length == 0)
			Toast.makeText(GridViewFile.this, "sd card does not exist", Toast.LENGTH_SHORT)
					.show();
		else {
			// Create a List collection, the elements of the List collection are 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>();
				// If the current File is a folder, use the folder icon; otherwise, use the file icon
				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());
				// add List item
				listItems.add(listItem);
			}
			// Create a SimpleAdapter
			SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
					R.layout.acheshi_item, new String[] { "icon", "fileName" },
					new int[] { R.id.imageView1, R.id.text_path });
			// Bit ListView set Adpter
			listView.setAdapter(simpleAdapter);
			try {
				textView.setText("The current path is: " + currentParent.getCanonicalPath());
			} catch (IOException e) {
				e.printStackTrace ();
			}
		}
	}

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

	// return to the upper menu
	private void onbey() {
		try {
			if (!MUSIC_PATH.equals(currentParent.getCanonicalPath())) {
				// Get the previous directory
				currentParent = currentParent.getParentFile();
				// list all files in the current directory
				currentFiles = currentParent.listFiles();
				// Update the ListView again
				inflateListView(currentFiles);
			} else {
				new AlertDialog.Builder(this)
						.setIcon(R.drawable.ic_launcher)
						.setTitle("Title")
						.setMessage("Are you sure you want to exit?")
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										finish();
									}
								})
						.setNegativeButton("Cancel",
								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 ();
	}

}

 

/**
 * Call the application corresponding to the system to open the file according to the path
 */

public class OpenFile {

    public static Intent openFile(String filePath){

        File file = new File(filePath);
        if(!file.exists()) return null;
            /* get the extension */
        String end=file.getName().substring(file.getName().lastIndexOf(".") + 1,file.getName().length()).toLowerCase();
            /* MimeType is determined by extension type */
        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 gets an intent for opening the APK file
    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)); // Stereotype
        intent.setDataAndType(uri,"*/*");
        return intent;
    }
    //Android gets an intent for opening the APK file
    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 gets an intent for opening the VIDEO file
    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 gets an intent for opening the AUDIO file
    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 gets an intent for opening the Html file
    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 gets an intent for opening the image file
    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 gets an intent for opening the PPT file
    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 gets an intent for opening an Excel file
    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 gets an intent for opening the Word file
    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 gets an intent for opening the CHM file
    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 gets an intent for opening a text file
    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 gets an intent for opening PDF files
    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;
    }
}

 

Don't forget to add permissions in AndroidManifest.xml!

<!-- SD card permissions-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326272910&siteId=291194637