Android开发 SharedPreferences读取不到最新数据..

最近公司的APP要实现进入APP的时候用户手动选择地区,然后在登录,这个时候其实是选择的对应的服务器地址,然而在实现过程中,我发现SharedPreferences在主页始终读取不到最新的服务器地址,然而登录页面的服务器地址又是最新更改的,比如说我刚开始进入的研发服务器,后面切换为测试服务器,然后里面的数据还是读取的 研发服务器的,后来打印发现主页服务器地址始终不是读取的当前最新地址,最后看了下,APP的两个service并没有运行在同一进程,读取不到数据,最后切换读取模式为多进程模式,然后就读取到了,

shared=getContext().getSharedPreferences("config",MODE_MULTI_PROCESS);

然而这样是读取到了最新的服务器地址,后来又发现当切换为桌面,把APP挂在后台,在切回前台的时候,APP的服务器地址又变回了之前的地址了,我想这个应该是要在保存状态的时候重新保存到别的变量中去吧,切回来的时候再去读取保存的变量来实现服务器地址的统一,后来干脆换了一种方式实现保存服务器地址,使用Properties键值对来保存服务器地址,这样没什么问题

package com.shangyi.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import com.shangyi.log.SyLog;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/** * 文件操作工具类 * * @version 1.0 */
public class FileUtils {
    private static final String TAG = FileUtils.class.getSimpleName();

    /** * 写入Properties信息 * * @param context 上下文对象 * @param fileName 文件名,不带后缀 * @param pKey 要保存数据的key * @param pValue 数据 * @throws IOException */
    public static void WriteProperties(Context context, String fileName, String pKey, String pValue) throws IOException {
        //this.getFilesDir(); 这个是得到当前app目录下的files目录路径
        //this.getCacheDir(); 这个是得到当前app目录下的cache目录路径
        String filePath = context.getFilesDir() + "/" + fileName + ".properties";

        File file = new File(filePath);
        if (!file.exists()) {//检查目录文件是否存在,不存在则创建
            file.createNewFile();
        }
        Properties pps = new Properties();
        InputStream in = new FileInputStream(filePath);
        pps.load(in);//从输入流中读取属性列表(键和元素对)
        OutputStream out = new FileOutputStream(filePath);//调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。 //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        pps.setProperty(pKey, pValue);
        //以适合使用 load 方法加载到 Properties 表中的格式,
        //将此 Properties 表中的属性列表(键和元素对)写入输出流
        pps.store(out, "Update " + pKey + " name");
    }


    /** * 根据Key读取Value * * @param context * @param fileName 文件名,不包含后缀 * @param key * @return */
    public static String getValueByKey(Context context, String fileName, String key) {
        String filePath = context.getFilesDir() + "/" + fileName + ".properties";
        Properties pps = new Properties();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            pps.load(in);
            String value = pps.getProperty(key);
            System.out.println("---------------------------------------------------------------------");
            System.out.println(key + " = " + value);
            System.out.println("---------------------------------------------------------------------");
            return value;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /** * 读取Properties的全部信息 * * @param context * @param fileName * @throws IOException */
    public static void getAllProperties(Context context, String fileName) throws IOException {
        String filePath = context.getFilesDir() + "/" + fileName + ".properties";
        Properties pps = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        pps.load(in);
        Enumeration en = pps.propertyNames(); //得到配置文件的名字
        while (en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
    }

    /** * 删除该目录下的文件 * * @param path */
    public static void delFile(String path) {
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /** * 根据文件名清空所有数据 * @param context * @param fileName * @throws IOException */
    public static void clearAllProperties(Context context,String fileName) throws IOException{
        String filePath = context.getFilesDir() + "/" + fileName + ".properties";
        boolean d=deleteFileWithPath(filePath);
       /* if(d){ ToastUtil.defaultToast(context.getApplicationContext(),"删除成功"); }else { ToastUtil.defaultToast(context.getApplicationContext(),"删除失败"); }*/
       /* Properties pps = new Properties(); InputStream in = new BufferedInputStream(new FileInputStream(filePath)); pps.load(in); pps.clear();//清楚所有数据*/
    }
    /** * 写文本文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下 * * @param context * @param fileName * @param content */
    public static void write(Context context, String fileName, String content) {
        if (content == null)
            content = "";
        try {
            //MODE_PRIVATE 默认模式,文件只可以被调用该方法的应用程序访问
            //MODE_APPEND 如果文件已存在就向该文件的末尾继续写入数据,而不是覆盖原来的数据。
            //MODE_WORLD_READABLE 赋予所有的应用程序对该文件读的权限。
            //MODE_WORLD_WRITEABLE 赋予所有的应用程序对该文件写的权限。
            FileOutputStream fos = context.openFileOutput(fileName,
                    Context.MODE_APPEND);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
            osw.write(content);
            fos.flush();
            osw.flush();
            osw.close();
            fos.close();
            SyLog.d(TAG, "写入成功");
// ToastUtil.defaultToast(context,"写入成功");
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.defaultToast(context.getApplicationContext(), "写入失败");
        }
    }

    /** * @param context * @param fileName * @param id */
    public static void writeId(Context context, String fileName, String id) {
        if (id == null)
            id = "-1";
        try {
            Log.d("id",id);
            //MODE_PRIVATE 默认模式,文件只可以被调用该方法的应用程序访问
            //MODE_APPEND 如果文件已存在就向该文件的末尾继续写入数据,而不是覆盖原来的数据。
            //MODE_WORLD_READABLE 赋予所有的应用程序对该文件读的权限。
            //MODE_WORLD_WRITEABLE 赋予所有的应用程序对该文件写的权限。
            FileOutputStream fos = context.openFileOutput(fileName,
                    Context.MODE_PRIVATE);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
            osw.write(id);
            fos.flush();
            osw.flush();
            osw.close();
            fos.close();
            SyLog.d(TAG, "写入成功");
// ToastUtil.defaultToast(context,"写入成功");
            Log.d("读取id",read(context,fileName));
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.defaultToast(context.getApplicationContext(), "写入失败");
        }
    }


    /** * 读取文本文件 * * @param context * @param fileName * @return */
    public static String read(Context context, String fileName) {
            try {
                FileInputStream in = context.openFileInput(fileName);
                InputStreamReader isr = new InputStreamReader(in);
                char[] data = new char[in.available()];
                isr.read(data);
                String s = new String(data);
                isr.close();
                in.close();
                SyLog.d(TAG, "读取成功");
// ToastUtil.defaultToast(context,s);
                return s;
            } catch (Exception e) {
                e.printStackTrace();
// ToastUtil.defaultToast(context.getApplicationContext(), "读取用户id失败,请重新登录");
            }
        return "-1";
    }


    /** * 读取输入流 * * @param inStream * @return */
    public static String readInStream(InputStream inStream) {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[512];
            int length = -1;
            while ((length = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, length);
            }
            outStream.close();
            inStream.close();
            return outStream.toString();
        } catch (IOException e) {
            Log.i("FileTest", e.getMessage());
        }
        return null;
    }

    public static File createFile(String folderPath, String fileName) {
        File destDir = new File(folderPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        return new File(folderPath, fileName + fileName);
    }

    /** * 向手机写图片 * * @param buffer * @param folder * @param fileName * @return */
    public static boolean writeFile(byte[] buffer, String folder,
                                    String fileName) {
        boolean writeSucc = false;

        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);

        String folderPath = "";
        if (sdCardExist) {
            folderPath = Environment.getExternalStorageDirectory()
                    + File.separator + folder + File.separator;
        } else {
            writeSucc = false;
        }

        File fileDir = new File(folderPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File file = new File(folderPath + fileName);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(buffer);
            writeSucc = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return writeSucc;
    }

    /** * 根据文件绝对路径获取文件名 * * @param filePath * @return */
    public static String getFileName(String filePath) {
        if (StringUtils.isEmpty(filePath))
            return "";
        return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
    }

    /** * 根据文件的绝对路径获取文件名但不包含扩展名 * * @param filePath * @return */
    public static String getFileNameNoFormat(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return "";
        }
        int point = filePath.lastIndexOf('.');
        return filePath.substring(filePath.lastIndexOf(File.separator) + 1,
                point);
    }

    /** * 获取文件扩展名 * * @param fileName * @return */
    public static String getFileFormat(String fileName) {
        if (StringUtils.isEmpty(fileName))
            return "";

        int point = fileName.lastIndexOf('.');
        return fileName.substring(point + 1);
    }

    /** * 获取文件大小 * * @param filePath * @return */
    public static long getFileSize(String filePath) {
        long size = 0;

        File file = new File(filePath);
        if (file != null && file.exists()) {
            size = file.length();
        }
        return size;
    }

    /** * 获取文件大小 * * @param size 字节 * @return */
    public static String getFileSize(long size) {
        if (size <= 0)
            return "0";
        java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
        float temp = (float) size / 1024;
        if (temp >= 1024) {
            return df.format(temp / 1024) + "M";
        } else {
            return df.format(temp) + "K";
        }
    }

    /** * 转换文件大小 * * @param fileS * @return B/KB/MB/GB */
    public static String formatFileSize(long fileS) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /** * 获取目录文件大小 * * @param dir * @return */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                dirSize += getDirSize(file); // 递归调用继续统计
            }
        }
        return dirSize;
    }

    /** * 获取目录文件个数 * * @param dir * @return */
    public long getFileList(File dir) {
        long count = 0;
        File[] files = dir.listFiles();
        count = files.length;
        for (File file : files) {
            if (file.isDirectory()) {
                count = count + getFileList(file);// 递归
                count--;
            }
        }
        return count;
    }

    public static byte[] toBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            out.write(ch);
        }
        byte buffer[] = out.toByteArray();
        out.close();
        return buffer;
    }

    /** * 检查文件是否存在 * * @param name * @return */
    public static boolean checkFileExists(String name) {
        boolean status;
        if (!name.equals("")) {
            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + name);
            status = newPath.exists();
        } else {
            status = false;
        }
        return status;
    }

    /** * 检查路径是否存在 * * @param path * @return */
    public static boolean checkFilePathExists(String path) {
        return new File(path).exists();
    }

    /** * 计算SD卡的剩余空间 * * @return 返回-1,说明没有安装sd卡 */
    public static long getFreeDiskSpace() {
        String status = Environment.getExternalStorageState();
        long freeSpace = 0;
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                File path = Environment.getExternalStorageDirectory();
                StatFs stat = new StatFs(path.getPath());
                long blockSize = stat.getBlockSize();
                long availableBlocks = stat.getAvailableBlocks();
                freeSpace = availableBlocks * blockSize / 1024;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return -1;
        }
        return (freeSpace);
    }

    /** * 新建目录 * * @param directoryName * @return */
    public static boolean createDirectory(String directoryName) {
        boolean status;
        if (null != directoryName && !directoryName.equals("")) {
            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + directoryName);
            status = newPath.mkdir();
            status = true;
        } else
            status = false;
        return status;
    }

    /** * 检查是否安装SD卡 * * @return */
    public static boolean checkSaveLocationExists() {
        String sDCardStatus = Environment.getExternalStorageState();
        boolean status;
        if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
            status = true;
        } else
            status = false;
        return status;
    }


    /** * 检查是否安装外置的SD卡 * * @return */
    public static boolean checkExternalSDExists() {

        Map<String, String> evn = System.getenv();
        return evn.containsKey("SECONDARY_STORAGE");
    }

    /** * 删除目录(包括:目录里的所有文件) * * @param fileName * @return */
    @SuppressLint("LongLogTag")
    public static boolean deleteDirectory(String fileName) {
        boolean status;
        SecurityManager checker = new SecurityManager();

        if (null != fileName && !fileName.equals("")) {
            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + File.separator + fileName);
            checker.checkDelete(newPath.toString());
            if (newPath.isDirectory()) {
                String[] listfile = newPath.list();
                // delete all files within the specified directory and then
                // delete the directory
                try {
                    for (int i = 0; i < listfile.length; i++) {
                        File deletedFile = new File(newPath.toString() + "/"
                                + listfile[i].toString());
                        deletedFile.delete();
                    }
                    newPath.delete();
                    Log.i("DirectoryManager deleteDirectory", fileName);
                    status = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    status = false;
                }

            } else
                status = false;
        } else
            status = false;
        return status;
    }

    /** * 删除文件 * * @param fileName * @return */
    @SuppressLint("LongLogTag")
    public static boolean deleteFile(String fileName) {
        boolean status;
        SecurityManager checker = new SecurityManager();

        if (!fileName.equals("")) {
            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + fileName);
            checker.checkDelete(newPath.toString());
            if (newPath.isFile()) {
                try {
                    Log.i("DirectoryManager deleteFile", fileName);
                    newPath.delete();
                    status = true;
                } catch (SecurityException se) {
                    se.printStackTrace();
                    status = false;
                }
            } else
                status = false;
        } else
            status = false;
        return status;
    }

    /** * 删除空目录 * <p/> * 返回 0代表成功 ,1 代表没有删除权限, 2代表不是空目录,3 代表未知错误 * * @return */
    public static int deleteBlankPath(String path) {
        File f = new File(path);
        if (!f.canWrite()) {
            return 1;
        }
        if (f.list() != null && f.list().length > 0) {
            return 2;
        }
        if (f.delete()) {
            return 0;
        }
        return 3;
    }

    /** * 重命名 * * @param oldName * @param newName * @return */
    public static boolean reNamePath(String oldName, String newName) {
        File f = new File(oldName);
        return f.renameTo(new File(newName));
    }

    /** * 删除文件 * * @param filePath */
    @SuppressLint("LongLogTag")
    public static boolean deleteFileWithPath(String filePath) {
        SecurityManager checker = new SecurityManager();
        File f = new File(filePath);
        checker.checkDelete(filePath);
        if (f.isFile()) {
            Log.i("DirectoryManager deleteFile", filePath);
            f.delete();
            return true;
        }
        return false;
    }

    /** * 清空一个文件夹 * * @param filePath */
    public static void clearFileWithPath(String filePath) {
        List<File> files = FileUtils.listPathFiles(filePath);
        if (files.isEmpty()) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                clearFileWithPath(f.getAbsolutePath());
            } else {
                f.delete();
            }
        }
    }

    /** * 获取SD卡的根目录 * * @return */
    public static String getSDRoot() {

        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    /** * 获取手机外置SD卡的根目录 * * @return */
    public static String getExternalSDRoot() {

        Map<String, String> evn = System.getenv();

        return evn.get("SECONDARY_STORAGE");
    }

    /** * 列出root目录下所有子目录 * * @param root * @return 绝对路径 */
    public static List<String> listPath(String root) {
        List<String> allDir = new ArrayList<String>();
        SecurityManager checker = new SecurityManager();
        File path = new File(root);
        checker.checkRead(root);
        // 过滤掉以.开始的文件夹
        if (path.isDirectory()) {
            for (File f : path.listFiles()) {
                if (f.isDirectory() && !f.getName().startsWith(".")) {
                    allDir.add(f.getAbsolutePath());
                }
            }
        }
        return allDir;
    }

    /** * 获取一个文件夹下的所有文件 * * @param root * @return */
    public static List<File> listPathFiles(String root) {
        List<File> allDir = new ArrayList<File>();
        SecurityManager checker = new SecurityManager();
        File path = new File(root);
        checker.checkRead(root);
        File[] files = path.listFiles();
        for (File f : files) {
            if (f.isFile())
                allDir.add(f);
            else
                listPath(f.getAbsolutePath());
        }
        return allDir;
    }

    public enum PathStatus {
        SUCCESS, EXITS, ERROR
    }

    /** * 创建目录 * * @param newPath */
    public static PathStatus createPath(String newPath) {
        File path = new File(newPath);
        if (path.exists()) {
            return PathStatus.EXITS;
        }
        if (path.mkdir()) {
            return PathStatus.SUCCESS;
        } else {
            return PathStatus.ERROR;
        }
    }

    /** * 截取路径名 * * @return */
    public static String getPathName(String absolutePath) {
        int start = absolutePath.lastIndexOf(File.separator) + 1;
        int end = absolutePath.length();
        return absolutePath.substring(start, end);
    }

    /** * 获取应用程序缓存文件夹下的指定目录 * * @param context * @param dir * @return */
    public static String getAppCache(Context context, String dir) {
        String savePath = context.getCacheDir().getAbsolutePath() + "/" + dir + "/";
        File savedir = new File(savePath);
        if (!savedir.exists()) {
            savedir.mkdirs();
        }
        savedir = null;
        return savePath;
    }


    /** * 读取SD卡中文本文件 * * @param fileName * @return */

    public static String readSDFile(String fileName) {
        StringBuffer sb = new StringBuffer();
        File file = new File(fileName);
        try {
            FileInputStream fis = new FileInputStream(file);
            int c;
            while ((c = fis.read()) != -1) {
                sb.append((char) c);
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
    原文作者:Android小屋
    原文地址: https://blog.csdn.net/pkandroid/article/details/52621861
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞