android 文件瀏覽器實現

cd33 9年前發布 | 5K 次閱讀 Java Android

項目列表

MainActivity實現代碼

package com.example.sdfileexplorer;

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set;

import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends Activity { ListView list; TextView path; Button parent; Map<String,String[]>arrlist=new HashMap(); //記錄當前父文件夾 File currentParent; //記錄當前文件夾下的所有文件數組 File[]currentFiles; boolean isExit=false; ArrayList<String> filepath=new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list=(ListView)findViewById(R.id.list); path=(TextView)findViewById(R.id.path); parent = (Button) findViewById(R.id.parent);

arrlist.put("fileEndingAudio",getResources().getStringArray(R.array.fileEndingAudio)); arrlist.put("fileEndingExcel",getResources().getStringArray(R.array.fileEndingExcel)); arrlist.put("fileEndingImage",getResources().getStringArray(R.array.fileEndingImage)); arrlist.put("fileEndingPackage",getResources().getStringArray(R.array.fileEndingPackage)); arrlist.put("fileEndingPdf",getResources().getStringArray(R.array.fileEndingPdf)); arrlist.put("fileEndingPPT",getResources().getStringArray(R.array.fileEndingPPT)); arrlist.put("fileEndingText",getResources().getStringArray(R.array.fileEndingText)); arrlist.put("fileEndingVideo",getResources().getStringArray(R.array.fileEndingVideo)); arrlist.put("fileEndingWebText",getResources().getStringArray(R.array.fileEndingWebText)); arrlist.put("fileEndingWord",getResources().getStringArray(R.array.fileEndingWord));

list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //如果是文件則不作處理 if(currentFiles[position].isFile()){ String extendName=getExtendFile(currentFiles[position]);///獲取文件拓展名 Intent intent=openFileIntent("."+extendName, currentFiles[position]); if(intent!=null){ startActivity(intent); }else{ Toast.makeText(MainActivity.this, "不存在打開此文件的應用!", Toast.LENGTH_LONG); } }else if(currentFiles[position].isDirectory()){ File[]tmp=currentFiles[position].listFiles(); if(tmp==null||tmp.length==0){ Toast.makeText(MainActivity.this, "當前文件夾為空文件夾", Toast.LENGTH_LONG).show(); //return; } currentParent=currentFiles[position]; currentFiles=tmp; inflateListView(currentFiles); } } });

path.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { // TODO Auto-generated method stub try { if(!(getRoot().equals("/storage/sdcard"))){//判斷是否到根目錄 //獲取上一級目錄 currentParent=currentParent.getCanonicalFile().getParentFile(); currentFiles=currentParent.listFiles(); inflateListView(currentFiles); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); parent.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); } }); }

public String getRoot(){//獲取根目錄的子字符串 String str=""; try { if(currentParent.getCanonicalPath().equals("/storage/sdcard")){ str="/storage/sdcard"; }else{ str=currentParent.getCanonicalPath().substring(0, currentParent.getCanonicalPath().length()-1); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK){ try{ if(getRoot().equals("/storage/sdcard")){ if(!isExit){ new Thread(){ public void run(){ int count=0; while(count<5000){ count++; } isExit=false; } }.start(); Toast.makeText(MainActivity.this, "在按一次退出SD卡文件瀏覽器", Toast.LENGTH_SHORT).show(); isExit=true; }else if(isExit){ finish(); } }else{ currentParent=currentParent.getCanonicalFile().getParentFile(); currentFiles=currentParent.listFiles(); inflateListView(currentFiles); } }catch(Exception e){ e.printStackTrace(); } }else if(keyCode==KeyEvent.KEYCODE_MENU){ if(getRoot().equals("/storage/sdcard")){ openOptionsMenu(); }

} return true; }

///根據拓展名獲取相應的Intent public Intent openFileIntent(String extendFileName,File file){ String intentType=null; for(String set:arrlist.keySet()){ String[]tmp=arrlist.get(set); for(int j=0;j<tmp.length;j++){ if(extendFileName.equals(tmp[j])){ if(set.equals("fileEndingAudio")){ return OpenFile.getAudioFileIntent(file); }else if(set.equals("fileEndingExcel")){ return OpenFile.getExcelFileIntent(file); }else if(set.equals("fileEndingImage")){ return OpenFile.getImageFileIntent(file); }else if(set.equals("fileEndingPackage")){ return OpenFile.getApkFileIntent(file); }else if(set.equals("fileEndingPdf")){ return OpenFile.getPdfFileIntent(file); }else if(set.equals("fileEndingPPT")){ return OpenFile.getPPTFileIntent(file); }else if(set.equals("fileEndingText")){ return OpenFile.getTextFileIntent(file); }else if(set.equals("fileEndingVideo")){ return OpenFile.getVideoFileIntent(file); }else if(set.equals("fileEndingWebText")){ return OpenFile.getHtmlFileIntent(file); }else if(set.equals("fileEndingWord")){ return OpenFile.getWordFileIntent(file); } break; } } } return null; }

@Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub Log.e("oncreateop", "fdadfad"); //menu=(Menu) LayoutInflater.from(MainActivity.this).inflate(R.menu.menu,null); MenuInflater inflater=new MenuInflater(this); inflater.inflate(R.menu.menu, menu); //獲取系統的SD卡的目錄 File root=null; if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){///獲取的是內置存儲卡 BufferedReader br=null; try { br=new BufferedReader(new FileReader(new File("/system/etc/vold.fstab"))); StringBuilder sb=new StringBuilder(""); String line=null; while((line=br.readLine())!=null){ String[]strtmp=line.split(" "); if(strtmp.length>0){ if(strtmp[0].equals("dev_mount")){ if(strtmp[3].equals("emmc@fat")){ Log.e("emmc@fat", "內置存儲卡"); menu.addSubMenu("內置存儲卡"); filepath.add(strtmp[2]); }else if(strtmp[3].equals("auto")){ Log.e("auto", "外置存儲卡"); menu.addSubMenu("外置存儲卡"); filepath.add(strtmp[2]); } } } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(IOException io){ io.printStackTrace(); } root=new File(Environment.getExternalStorageDirectory().getPath()); if(root.exists()){ currentParent=root; currentFiles=currentParent.listFiles(); //使用當前目錄下的全部文件、文件夾來填充ListView inflateListView(currentFiles); } }else{ Toast.makeText(MainActivity.this, "手機中沒有SD卡", Toast.LENGTH_LONG).show(); } return true; }

@Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getTitle().toString().trim().equals("內置存儲卡")){ currentParent=new File(filepath.get(0)); currentFiles=currentParent.listFiles(); inflateListView(currentFiles); }else if(item.getTitle().toString().trim().equals("外置存儲卡")){ currentParent=new File(filepath.get(1)); currentFiles=currentParent.listFiles(); inflateListView(currentFiles); }

return true; }

private void inflateListView(File[]files){ List<Map<String,Object>>listItems=new ArrayList<Map<String,Object>>(); if(files!=null){ for(int i=0;i<files.length;i++){ Map<String,Object>listItem=new HashMap<String, Object>(); if(files[i].isDirectory()){ listItem.put("icon", R.drawable.folder); }else if(files[i].isFile()){ listItem.put("icon", R.drawable.file); } listItem.put("filename", files[i].getName()); listItems.add(listItem); } //SimpleAdapter adapter=new SimpleAdapter(MainActivity.this, listItems,R.layout.line, new String[]{"icon","filename"}, new int[]{R.id.icon,R.id.file_name}); } MyAdapter adapter=new MyAdapter(MainActivity.this, listItems); list.setAdapter(adapter); try { path.setText("當前路徑為:"+currentParent.getCanonicalPath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

public String getExtendFile(File file){ String path=file.getPath(); String[]strtmp=path.split("\."); if(strtmp.length>0){ return strtmp[strtmp.length-1]; }else{ return null; }

} }

class MyAdapter extends BaseAdapter{ Context context; List<Map<String,Object>>listItems; public MyAdapter(Context context,List<Map<String,Object>>listItems){ this.context=context; this.listItems=listItems; } @Override public int getCount() { // TODO Auto-generated method stub return listItems.size(); }

@Override public Object getItem(int position) { // TODO Auto-generated method stub return listItems.get(position); }

@Override public long getItemId(int position) { // TODO Auto-generated method stub return position; }

@Override public View getView(int position, View convertView, ViewGroup parent) {

convertView=LayoutInflater.from(context).inflate(R.layout.line,null); ImageView image=(ImageView) convertView.findViewById(R.id.icon); TextView textView=(TextView)convertView.findViewById(R.id.file_name); if(listItems!=null&&listItems.size()>0){ image.setImageResource(Integer.parseInt(listItems.get(position).get("icon").toString())); textView.setText(listItems.get(position).get("filename").toString()); textView.setTextColor(Color.WHITE); }

return convertView; }

}

OpenFile實現代碼

package com.example.sdfileexplorer;

import java.io.File;

import android.content.Intent; import android.net.Uri;

public class OpenFile { //android獲取一個用于打開HTML文件的intent public static Intent getHtmlFileIntent(File file) { Uri uri = Uri.parse(file.toString()).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(file.toString()).build(); Intent intent = new Intent("android.intent.action.VIEW"); intent.setDataAndType(uri, "text/html"); return intent; } //android獲取一個用于打開圖片文件的intent public static Intent getImageFileIntent(File file) { 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(file); intent.setDataAndType(uri, "image/*"); return intent; } //android獲取一個用于打開PDF文件的intent public static Intent getPdfFileIntent(File file) { 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(file); intent.setDataAndType(uri, "application/pdf"); return intent; } //android獲取一個用于打開文本文件的intent public static Intent getTextFileIntent(File file) {
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(file); intent.setDataAndType(uri, "text/plain"); return intent; }

//android獲取一個用于打開音頻文件的intent public static Intent getAudioFileIntent(File file) { 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(file); intent.setDataAndType(uri, "audio/"); return intent; } //android獲取一個用于打開視頻文件的intent public static Intent getVideoFileIntent(File file) { 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(file); intent.setDataAndType(uri, "video/"); return intent; }

//android獲取一個用于打開CHM文件的intent
public static Intent getChmFileIntent(File file)
{
 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(file);
 intent.setDataAndType(uri, "application/x-chm");
 return intent;
}




//android獲取一個用于打開Word文件的intent public static Intent getWordFileIntent(File file) { 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(file); intent.setDataAndType(uri, "application/msword"); return intent; } //android獲取一個用于打開Excel文件的intent public static Intent getExcelFileIntent(File file) { 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(file); intent.setDataAndType(uri, "application/vnd.ms-excel"); return intent; } //android獲取一個用于打開PPT文件的intent public static Intent getPPTFileIntent(File file) { 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(file); intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); return intent; } //android獲取一個用于打開apk文件的intent public static Intent getApkFileIntent(File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); return intent; } }</pre>


運行效果圖

 本文由用戶 cd33 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!