我的PDF阅读器之ChoosePDFActivity解析

所有的解析都放在代码的解析中了,直接看代码吧

package com.artifex.mupdfdemo;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.view.View;
import android.widget.ListView;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * 选择文件类
 */
public class ChoosePDFActivity extends ListActivity {
    public static final String TAG = ChoosePDFActivity.class.getName();

    static private File  mDirectory;
    //保存上一级目录的名称,及其滑动到的地方
    static private Map<String, Integer> mPositions = new HashMap<String, Integer>();
    private File         mParent;//父目录
    private File []      mDirs;//当前父目录下的文件夹
    private File []      mFiles;//当前父目录下的文件
    private Handler         mHandler;
    private Runnable     mUpdateFiles;
    private ChoosePDFAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String storageState = Environment.getExternalStorageState();

        if (!Environment.MEDIA_MOUNTED.equals(storageState)
                && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(storageState))
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.no_media_warning);
            builder.setMessage(R.string.no_media_hint);
            AlertDialog alert = builder.create();
            alert.setButton(AlertDialog.BUTTON_POSITIVE,"Dismiss",
                    new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
            alert.show();
            return;
        }

        //把download文件夹作为根目录
        if (mDirectory == null)
            mDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        // Create a list adapter...
        adapter = new ChoosePDFAdapter(getLayoutInflater());
        setListAdapter(adapter);

        // ...that is updated dynamically when files are scanned
        mHandler = new Handler();
        mUpdateFiles = new Runnable() {
            public void run() {
                Resources res = getResources();
                String appName = res.getString(R.string.app_name);
                String version = res.getString(R.string.version);
                String title = res.getString(R.string.picker_title);
                setTitle(String.format(title, appName, version, mDirectory));

                mParent = mDirectory.getParentFile();

                //选择文件夹
                mDirs = mDirectory.listFiles(new FileFilter() {

                    public boolean accept(File file) {
                        return file.isDirectory();
                    }
                });
                if (mDirs == null)
                    mDirs = new File[0];


                //fileFilter 一个选择文件的抽象类
                //选择文件
                mFiles = mDirectory.listFiles(new FileFilter() {

                    public boolean accept(File file) {
                        if (file.isDirectory())
                            return false;
                        String fname = file.getName().toLowerCase();
                        if (fname.endsWith(".pdf"))
                            return true;
                        if (fname.endsWith(".xps"))
                            return true;
                        if (fname.endsWith(".cbz"))
                            return true;
                        return false;
                    }
                });
                if (mFiles == null)
                    mFiles = new File[0];

                //排序文件和文件夹
                Arrays.sort(mFiles, new Comparator<File>() {
                    public int compare(File arg0, File arg1) {
                        return arg0.getName().compareToIgnoreCase(arg1.getName());
                    }
                });

                Arrays.sort(mDirs, new Comparator<File>() {
                    public int compare(File arg0, File arg1) {
                        return arg0.getName().compareToIgnoreCase(arg1.getName());
                    }
                });

                adapter.clear();//清除之前的东西
                //添加内容
                if (mParent != null)//添加返回上一层的按钮
                    adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.PARENT, "[Up one level]"));
                //添加目录和文件
                for (File f : mDirs)
                    adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.DIR, f.getName()));
                for (File f : mFiles)
                    adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.DOC, f.getName()));

                lastPosition();//?????不知道干嘛
            }
        };

        // Start initial file scan...
        mHandler.post(mUpdateFiles);

        // ...and observe the directory and scan files upon changes.
        //fileObserver 一个监听文件变化的抽象类
        FileObserver observer = new FileObserver(mDirectory.getPath(), FileObserver.CREATE | FileObserver.DELETE) {
            public void onEvent(int event, String path) {
                mHandler.post(mUpdateFiles);
            }
        };
        observer.startWatching();
    }

    /**
     * 判读这个目录是否之前来过的,如果是就回到上次滑动到的地方
     */
    private void lastPosition() {
        String p = mDirectory.getAbsolutePath();
        if (mPositions.containsKey(p)){
            getListView().setSelection(mPositions.get(p));
//            Log.v(TAG,p+"--->"+mPositions.get(p)); //debug
        }

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        //当用户点击的时候表示进入了新目录,记录下旧目录下的信息
        mPositions.put(mDirectory.getAbsolutePath(), getListView().getFirstVisiblePosition());

        //当mParent 为空时表示到了根目录,下面的代码不会执行。
        //当position为0时,表示为返回上一层目录
        if (position < (mParent == null ? 0 : 1)) {
            mDirectory = mParent;
            mHandler.post(mUpdateFiles);
            return;
        }

        //因为listView中多了个返回上一层,所以具体的位置应该是position-1
        position -= (mParent == null ? 0 : 1);

        //如果在目录的范围内,就更新目录
        if (position < mDirs.length) {
            mDirectory = mDirs[position];
            mHandler.post(mUpdateFiles);
            return;
        }

        //算出文件的位置
        position -= mDirs.length;

        Uri uri = Uri.parse(mFiles[position].getAbsolutePath());
        Intent intent = new Intent(this,MuPDFActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPositions.put(mDirectory.getAbsolutePath(), getListView().getFirstVisiblePosition());
    }
}

下一步,我将会在这个的基础上弄一个自己的文件浏览器

    原文作者:@47
    原文地址: https://www.cnblogs.com/Jabba93/p/3197087.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞