Android traverse to get files in Office format (Word, Excel, PPT, PDF) and open them

This case is mainly to imitate QQ to load WPS (Word, Excel, PPT) local files that can be opened and viewed, loaded using ListView, using threads to scan all directories under SD card to load files in the specified Word, Excel, PPT and other formats, ListView list display, Click Item to call the system application to open.

Effect picture:

         

Code:

 

public class MainActivity extends AppCompatActivity {

    public ProgressDialog dialog;
    private ListView mListview;
    private Context context;
    private List<AddFileInfo> list=new ArrayList<AddFileInfo>();
    private String filePath = Environment.getExternalStorageDirectory().toString() + File.separator;
    private static Adapter adapter;
    private ACache aCache;
    private String fileDate="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);

        mListview=(ListView) findViewById(R.id.listview);
        context=this;
        aCache=ACache.get(this);
        onLoad();
    }
    public void onLoad() {
        adapter=new Adapter(MainActivity.this);
        String string=aCache.getAsString("file");
        if(string==null)
        {
            showProgress();
            new MyThread().start();
        }else{
            String[] str=string.split(",");

            for (int i=0;i<str.length;i++)
            {
                File f = new File(str[i]);
                if(f.exists()) {
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(f);
                        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date(f.lastModified()));
                        AddFileInfo info = new AddFileInfo(f.getName(), Long.valueOf(fis.available()), time, false, f.getAbsolutePath());
                        fileDate += f.getAbsolutePath() + ",";
                        list.add(info);
                    } catch (Exception e) {
                        return;
                    }
                }
            }
        }
        mListview.setOnItemClickListener(onItemClickListener);
        mListview.setAdapter(adapter);
    }

    AdapterView.OnItemClickListener onItemClickListener=new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(OpenFile.openFile(list.get(position).getPath()));
        }
    };



    public class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                doSearch (filePath);
                Thread.sleep(2000);
                Message msg=new Message();
                msg.what=1;
                msg.obj=1;
                handler.sendMessage(msg);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }

        }
    }

    Handler handler = new Handler () {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                dismissProgress();
                adapter.notifyDataSetChanged();
                aCache.put("file",fileDate.substring(0,(fileDate.length()-1)),600);
            }
        }
    };


    /****
     * Calculate file size
     * @param length
     * @return
     */
    public static String ShowLongFileSzie(Long length)
    {
        if(length>=1048576)
        {
            return (length/1048576)+"MB";
        }
        else if(length>=1024)
        {
            return (length/1024)+"KB";
        }
        else if(length<1024) {
            return length + "B";
        }else{
            return "0KB";
        }
    }



    /****
     * Recursive algorithm to get local files
     * @param path
     */
    private void doSearch( String path) {
        File file = new File(path);

        if (file.exists()) {
            if (file.isDirectory()) {
                File[] fileArray = file.listFiles();
                for (File f : fileArray) {

                    if (f.isDirectory()) {
                        doSearch (f.getPath ());
                    }
                    else {
                        if(f.getName().endsWith(".ppt") || f.getName().endsWith(".pptx") || f.getName().endsWith(".docx")
                                || f.getName().endsWith(".xls") || f.getName().endsWith(".doc"))
                        {
                            FileInputStream fis = null;
                            try {
                                fis = new FileInputStream(f);
                                String time=new SimpleDateFormat("yyyy-MM-dd").format(new Date(f.lastModified()));
                                AddFileInfo  info=new AddFileInfo(f.getName(),Long.valueOf(fis.available()),time,false,f.getAbsolutePath());
                                list.add(info);
                                fileDate += f.getAbsolutePath() + ",";
                                System.out.println("File name: " + f.getName());
                                System.out.println("Does the file exist: " + f.exists());
                                System.out.println("The relative path of the file: " + f.getPath());
                                System.out.println("Absolute path of file: " + f.getAbsolutePath());
                                System.out.println("File can be read: " + f.canRead());
                                System.out.println("File can be written: " + f.canWrite());
                                System.out.println("File parent path: " + f.getParent());
                                System.out.println("File size: " + f.length() + "B");
                                System.out.println("File last modified time: " + new Date(f.lastModified()));
                                System.out.println("Is it a file type: " + f.isFile());
                                System.out.println("Is it a folder type: " + f.isDirectory());
                            } catch (Exception e) {
                                e.printStackTrace ();
                            }
                        }
                    }
                }
            }
        }
    }

 /***
     * start up
     */
    public void showProgress()
    {
        if(dialog==null)
        {
            dialog=new ProgressDialog(MainActivity.this);
        }
        dialog.showMessage("Loading");
    }

    /***
     * closure
     */
    public void  dismissProgress()
    {
        if(dialog==null)
        {
            dialog=new ProgressDialog(this);
        }
        dialog.dismiss();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy ();
    }
}

 

 

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" />

 

 

Source code click to download

 

 

Guess you like

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