首页 > 移动平台 > 详细

AppDir【创建缓存目录】

时间:2017-10-07 22:34:58      阅读:1236      评论:0      收藏:0      [点我收藏+]

版权声明:本文为博主原创文章,未经博主允许不得转载。

前言

创建缓存目录

    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卡中的自定义目录,所以还是需要权限的。

效果图

暂不需要

代码分析

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

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

使用步骤

一、项目组织结构图

技术分享

注意事项:

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

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

二、导入步骤

将AppDir、FileUtils复制到项目中

技术分享
package com.why.project.appdirdemo.utils;

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

import java.io.File;

/**
 * Created by HaiyuKing
 * Used 创建缓存目录
 */

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();
    }

    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;
    }

    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文件中声明权限

<?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下载地址

https://github.com/haiyuKing/AppDirDemo

AppDir【创建缓存目录】

原文:http://www.cnblogs.com/whycxb/p/7635902.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!