Android实现文件目录的选择并保存到SharedPreferences中(适配6.0后的权限)

1>使用AndPermission权限开源框架

    /*permission*/
    compile 'com.yanzhenjie:permission:1.0.6'

2>使用AndPermission申请权限

            AndPermission.with(this)
                    .requestCode(100) //requestCode码对应权限申请成功或失败
                    .permission(
                            // 多个权限,以数组的形式传入。
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .rationale(rationaleListener)
                    .callback(this)
                    .start();
        
    @PermissionYes(100) //100与上边的requestCode
    private void getPermissionYes(List grantedPermissions) {
        // TODO 申请权限成功。 之后获取该目录中所有文件和文件夹
        getFileDir(paths.get(index));
    }

    @PermissionNo(100) //100与上边的requestCode一致
    private void getPermissionNo(List deniedPermissions) {
        // TODO 申请权限失败。

        // 是否有不再提示并拒绝的权限。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {

            // 第二种:用自定义的提示语。
            AndPermission.defaultSettingDialog(this, 400)
                    .setTitle("权限申请失败")
                    .setMessage("您拒绝了我们必要的一些权限,已经没法愉快的玩耍了,请在设置中授权!")
                    .setPositiveButton("去设置")
                    .show();

        }
    }


    /**
     * Rationale支持,这里自定义对话框。
     */
    private RationaleListener rationaleListener = (requestCode, rationale) -> {
        AlertDialog.newBuilder(this)
                .setTitle("友好提醒")
                .setMessage("您已拒绝过读取SDK权限,沒有SDK权限无法使用该功能,请授权!")
                .setPositiveButton("授权", (dialog, which) -> {
                    rationale.resume();
                })
                .setNegativeButton("拒绝", (dialog, which) -> {
                    rationale.cancel();
                }).show();
    };
        
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 400: { // 这个400就是你上面传入的数字。getPermissionNo方法中的400

                // 你可以在这里检查你需要的权限是否被允许,并做相应的操作。
                getFileDir(paths.get(index));
                break;
            }
        }
    }

3>编写listview的item.xml文件



    
        
        
        
        
    

4>编写自定义adapter

package com.supermap.onsiteinspection.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.supermap.onsiteinspection.R;

import java.io.File;
import java.util.List;

/**
 * Created by XueQing Wang on 2018/5/14.
 */

public class FileAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Bitmap mIcon1;
    private Bitmap mIcon2;
    private Bitmap mIcon3;
    private Bitmap mIcon4;
    private List items;
    private List paths;

    public FileAdapter(Context context, List it, List pa) {
        mInflater = LayoutInflater.from(context);
        items = it;
        paths = pa;
        mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.mc_arrow_normal_black);
        mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.mc_arrow_normal_black);
        mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.folder);
        mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.paper);
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

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

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.file_row, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        File f = new File(paths.get(position).toString());
        if (items.get(position).toString().equals("b1")) {
            holder.text.setText("返回根目录..");
            holder.icon.setImageBitmap(mIcon1);
        } else if (items.get(position).toString().equals("b2")) {
            holder.text.setText("返回上一层..");
            holder.icon.setImageBitmap(mIcon2);
        } else {
            holder.text.setText(f.getName());
            if (f.isDirectory()) {
                holder.icon.setImageBitmap(mIcon3);
            } else {
                holder.icon.setImageBitmap(mIcon4);
            }
        }
        return convertView;
    }

    private class ViewHolder {
        TextView text;
        ImageView icon;
    }
}

5>编写listview.xml文件




    
    
    
    
    
    
        

6>在需要跳转文件夹的activity中的代码

                Intent intent = new Intent(getContext(), FileManageActivity.class);
                startActivityForResult(intent, 2);


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2 && resultCode == 2) {
            Bundle bundle = null;
            if (data != null && (bundle = data.getExtras()) != null) {
                String file = bundle.getString("file");
                SharedPreferencesUtil.setString(getContext(),"tvImgPath",file);
                tvImgPath.setText(file);
            }
        }
    }

7>完整的文件夹页面的activity代码

package com.supermap.onsiteinspection.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.supermap.onsiteinspection.R;
import com.supermap.onsiteinspection.adapter.FileAdapter;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FileManageActivity extends AppCompatActivity implements ListView.OnItemClickListener {

    @BindView(R.id.mPath)
    TextView mPath;
    @BindView(android.R.id.list)
    ListView list;
    @BindView(R.id.buttonConfirm)
    Button buttonConfirm;
    @BindView(R.id.buttonCancle)
    Button buttonCancle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private List items = null;
    private List paths = null;
    private String rootPath = "/";
    private String curPath = "/";
    private final static String TAG = "bb";
    int index;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_file_manage);
        ButterKnife.bind(this);
        //设置toolbar
        toolbar.setTitle("目录选择");
        buttonConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回原activity并携带路径数据
                Intent data = new Intent(FileManageActivity.this, MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("file", curPath);
                data.putExtras(bundle);
                setResult(2, data);
                finish();
            }
        });

        buttonCancle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        getFileDir(rootPath);
    }

    private void getFileDir(String filePath) {
        mPath.setText(filePath);
        items = new ArrayList();
        paths = new ArrayList();
        File f = new File(filePath);
        File[] files = f.listFiles();
        if (!filePath.equals(rootPath)) {
            items.add("b1");
            paths.add(rootPath);
            items.add("b2");
            paths.add(f.getParent());
        }
        if(files!=null){
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                items.add(file.getName());
                paths.add(file.getPath());
            }
        }


        list.setAdapter(new FileAdapter(this, items, paths));
        list.setOnItemClickListener(this);
    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        File file = new File(paths.get(position));
        if (file.isDirectory()) {
            curPath = paths.get(position);
            this.index = position;
            AndPermission.with(this)
                    .requestCode(100)
                    .permission(
                            // 多个权限,以数组的形式传入。
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .rationale(rationaleListener)
                    .callback(this)
                    .start();
        } else {
            //可以打开文件
        }
    }


    @PermissionYes(100)
    private void getPermissionYes(List grantedPermissions) {
        // TODO 申请权限成功。
        getFileDir(paths.get(index));
    }

    @PermissionNo(100)
    private void getPermissionNo(List deniedPermissions) {
        // TODO 申请权限失败。

        // 是否有不再提示并拒绝的权限。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {

            // 第二种:用自定义的提示语。
            AndPermission.defaultSettingDialog(this, 400)
                    .setTitle("权限申请失败")
                    .setMessage("您拒绝了我们必要的一些权限,已经没法愉快的玩耍了,请在设置中授权!")
                    .setPositiveButton("去设置")
                    .show();

        }
    }


    /**
     * Rationale支持,这里自定义对话框。
     */
    private RationaleListener rationaleListener = (requestCode, rationale) -> {
        AlertDialog.newBuilder(this)
                .setTitle("友好提醒")
                .setMessage("您已拒绝过读取SDK权限,沒有SDK权限无法使用该功能,请授权!")
                .setPositiveButton("授权", (dialog, which) -> {
                    rationale.resume();
                })
                .setNegativeButton("拒绝", (dialog, which) -> {
                    rationale.cancel();
                }).show();
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 400: { // 这个400就是你上面传入的数字。
                // 你可以在这里检查你需要的权限是否被允许,并做相应的操作。
                getFileDir(paths.get(index));
                break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }
}




你可能感兴趣的:(Android)