AppDir【创建缓存目录】【建议使用这个工具类】

版权声明:本文为HaiyuKing原创文章,转载请注明出处!

前言

创建缓存目录

    public static String APP_CACHE = "";//   /storage/emulated/0/Android/data/{package}/cache/
    public static String IMAGE = "";//       /storage/emulated/0/Android/data/{package}/cache/image
    public static String CAMERA = "";//      /storage/emulated/0/Android/data/{package}/cache/camera
    public static String GIF = "";//         /storage/emulated/0/Android/data/{package}/cache/gif
    public static String FUND = "";//        /storage/emulated/0/Android/data/{package}/cache/fund
    public static String CRASH = "";//       /storage/emulated/0/Android/data/{package}/files/crash
    public static String PLAYER = "";//      /storage/emulated/0/Android/data/{package}/files/player
    public static String P2P = "";//         /storage/emulated/0/Android/data/{package}/files/p2p
    public static String DOWNLOAD = "";//    /storage/emulated/0/Android/data/{package}/files/download或者自定义的目录

  

注意:因为创建目录都是在/storage/emulated/0/Android/data/{package}目录中,所以本来不需要权限;但是下载目录有可能需要使用SD卡中的自定义目录,所以还是需要权限的。【20191124,不需要权限】

效果图

暂不需要

代码分析

AppDir : 自定义需要创建的缓存目录

FileUtils : 创建目录、删除目录下所有文件、获取目录下第一个文件path

使用步骤

一、项目组织结构图

注意事项:

1、  导入类文件后需要change包名以及重新import R文件路径

2、  Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖

二、导入步骤

将AppDir、FileUtils复制到项目中

【20191124更新】

package com.why.project.appdirdemo.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;

import java.io.File;

/**
 * Created by HaiyuKing
 * Used 创建缓存目录
 * 安卓手机的存储分为 2 部分,内部存储 ( Internal ) 和外部存储( External ):
 * 内部存储是指系统的存储空间,没有root是访问不到的呦亲,比如sharedPreferenced或者database都是保存在这里面的。
 * 外部存储,又分为 2 部分:【操作外部存储你首先需要以下权限:WRITE_EXTERNAL_STORAGE,不过Android Q之后不再需要申请该权限】
 * 机器自带的存储【ExternalStorage】,也就是手机厂商常说的16G,32G,64G之类的存储空间。
 * SD卡,其实正确叫法应该是TF卡,就是可插拔的那个小东西。
 * 参考资料:https://www.jianshu.com/p/116025bf51f7
 */

public class AppDir {

    public static final String TAG = AppDir.class.getName();

    private static Context mContext;

    enum Type {
        CACHE,FILE;
    }

    public static String APP_CACHE = "";//   /storage/emulated/0/Android/data/{package}/cache/
    public static String IMAGE = "";//       /storage/emulated/0/Android/data/{package}/cache/image
    public static String CAMERA = "";//      /storage/emulated/0/Android/data/{package}/cache/camera
    public static String GIF = "";//         /storage/emulated/0/Android/data/{package}/cache/gif
    public static String FUND = "";//        /storage/emulated/0/Android/data/{package}/cache/fund
    public static String CRASH = "";//       /storage/emulated/0/Android/data/{package}/files/crash
    public static String PLAYER = "";//      /storage/emulated/0/Android/data/{package}/files/player
    public static String P2P = "";//         /storage/emulated/0/Android/data/{package}/files/p2p
    public static String DOWNLOAD = "";//    /storage/emulated/0/Android/data/{package}/files/download或者自定义的目录

    public static AppDir getInstance(Context mContext){
        AppDir appDir = new AppDir();
        appDir.mContext = mContext;
        initDatas();
        return appDir;
    }

    private static void initDatas(){
        APP_CACHE = createPath("APP_CACHE", 0, "", Type.CACHE);
        IMAGE =createPath("IMAGE", 1, "image", Type.CACHE);
        CAMERA = createPath("CAMERA", 2, "camera", Type.CACHE);
        GIF = createPath("GIF", 3, "gif", Type.CACHE);
        FUND = createPath("FUND", 4, "fund", Type.CACHE);
        CRASH = createPath("CRASH", 5, "crash", Type.FILE);
        PLAYER = createPath("PLAYER", 6, "player", Type.FILE);
        P2P = createPath("P2P", 8, "p2p", Type.FILE);
        //DOWNLOAD = createDownloadPath();//20191124,该方法不再使用
        DOWNLOAD = createPath("download", 9, "download", Type.FILE);
    }

    private static String createPath(String name, int index, String subpath, Type p) {
        String cachePath = mContext.getExternalCacheDir() + File.separator;//一般存放临时缓存数据
        String filePath = mContext.getExternalFilesDir(null) + File.separator;//一般放一些长时间保存的数据
        String path = p == Type.CACHE ? cachePath + subpath : filePath + subpath;

        //Log.e(TAG,"{AppDir}name="+name+";path="+path);
        FileUtils.makeDirs(path);//创建目录
        return path;
    }

    /**
     * 20191124
     * 这个方法不建议使用,留在这里作为备份*/
    private static String createDownloadPath() {
        String path = "";
        // 判断sd卡是否存在
        boolean sdCardExit = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        //Log.e(TAG,"{AppDir}sdCardExit="+sdCardExit);
        if (sdCardExit) {
            if(Build.VERSION.SDK_INT >= 19) {//如果版本大于19,则直接在缓存目录中创建download目录
                File[] files = mContext.getExternalFilesDirs("download");
                if(files != null && files.length >= 1 && files[0] != null) {
                    path = files[0].getAbsolutePath();//  /storage/emulated/0/Android/data/{package}/files/download
                }
            }else {
                path = Environment.getExternalStorageDirectory() + File.separator + "why/download";//使用自定义的download目录
            }
        }else{
            path = Environment.getDataDirectory() + File.separator + "why/download";//使用自定义的download目录
        }
        //Log.e(TAG,"{AppDir}DOWNLOAD"+";path="+path);
        FileUtils.makeDirs(path);//创建目录
        return path;
    }


}
AppDir

 

package com.why.project.appdirdemo.utils;

import android.text.TextUtils;

import java.io.File;

/**
 * Created by HaiyuKing
 * Used 配合APPDir的文件工具类
 */

public class FileUtils {

    //创建目录
    public static boolean makeDirs(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        }

        File folder = new File(filePath);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }

    //获取目录名
    public static String getFolderName(String filePath) {

        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
    }

    /**删除所有文件*/
    public static void deleteAllFile(String filePath)
    {
        if(!TextUtils.isEmpty(filePath)) {
            deleteAllFiles(new File(filePath));
        }
    }

    /**删除所有文件*/
    public static void deleteAllFiles(File root)
    {
        File[] arrayOfFile = root.listFiles();
        if (arrayOfFile != null)
        {
            for(int j = 0;j < arrayOfFile.length;j++){
                File file = arrayOfFile[j];
                if (file.isDirectory())
                {
                    deleteAllFiles(file);
                    file.delete();
                }else if(file.exists()){
                    deleteAllFiles(file);
                    file.delete();
                }
            }
        }
    }

    /**获取第一个文件的完整路径*/
    public static String firstFile(String parentPath){
        File[] arrayOfFile = new File(parentPath).listFiles();
        String firstFilePath = "";
        if (arrayOfFile != null)
        {
            File file0 = arrayOfFile[0];
            firstFilePath = file0.getPath();
        }
        return firstFilePath;
    }
}
FileUtils

在AndroidManifest.xml文件中声明权限【20191124,不需要权限】

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.why.project.appdirdemo">

    <!-- =================AppDir用到的权限========================== -->
    <!-- 允许程序读取外部存储文件 -->
    <!--<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>-->
    <!-- 允许程序写入外部存储,如SD卡上写文件 -->
    <!--<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>-->

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

 

添加运行时权限的处理(本demo中采用的是修改targetSDKVersion=22)

三、使用方法

package com.why.project.appdirdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.why.project.appdirdemo.utils.AppDir;
import com.why.project.appdirdemo.utils.FileUtils;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String pngFilePath = AppDir.getInstance(this).IMAGE + File.separator + System.currentTimeMillis() + ".png";
        Log.e(TAG,"pngFilePath="+pngFilePath);//  /storage/emulated/0/Android/data/com.why.project.appdirdemo/cache/image/1507125270183.png

        //删除目录下所有文件
        //FileUtils.deleteAllFile(AppDir.getInstance(this).IMAGE);

        //获取目录下第一个文件
        //String pngPath = FileUtils.firstFile(AppDir.getInstance(this).IMAGE);
    }
}

混淆配置

参考资料

暂时空缺

项目demo下载地址

暂不需要

posted @ 2017-10-07 22:12  HaiyuKing  阅读(3230)  评论(0编辑  收藏  举报