本身整理的Android工具方法

package www.tydic.com.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;

import com.yalantis.ucrop.UCrop;

import java.io.BufferedOutputStream;
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.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by LIUREN on 2017/2/16.
 */

public class PhoneUtils {
    /**
     * 使用方式:
     *
     * 1.獲取拍照原圖Bitmap:  PhoneUtils.onInitPhoneResult(this,requestCode,resultCode,data,"init.jpg")
     *   參數列表:上下文環境,請求碼,響應碼,返回的數據,圖片名稱
     *   注:請求碼,響應碼,返回的數據是onActivityResult()方法的參數
     * 2.獲取必定壓縮比例的原圖
     *   (1)方式一:拍照保存:PhoneUtils.onInitPhoneResult(this,requestCode,resultCode,data,"init.jpg")
     *                將拍照保存路徑下的照片進行處理  PhoneUtils.getBitmapOption(Environment.getExternalStorageDirectory() + "/phone/init.jpg", 20))
     *                參數:拍照保存的全路徑,縮放比列(20表示縮放比爲原圖的1/20)
     *   (2)方式二:將現有的bitmap進行壓縮處理:
     *                將bitmap保存:PhoneUtils.saveBitmapFile(bitmap,filePath);
     *                   參數:有效的bitmap,保存的全路徑
     *                將保存路徑下的bitmap進行壓縮:PhoneUtils.getBitmapOption(filePath, 20))
     *                   參數:保存的全路徑,縮放比列
     * 3.保存一個bitmap:PhoneUtils.saveBitmapFile(bitmap,filePath);
     *                   參數:有效的bitmap,保存的全路徑
     * 4.縮放一個一個路徑下的bitmap:PhoneUtils.getBitmapOption(filePath, 20))
     *                   參數:保存的全路徑,縮放比列
     * 5.獲取一個拍照縮略圖:
     *                拍照:PhoneUtils.getAbbreviationsPhone(this);
     *                在onActivityResult()中PhoneUtils.onAbbreviationsPhoneResult(this,requestCode,resultCode,data)
     *                   參數:上下文,請求碼,響應碼,返回數據
     * 6.獲取相冊選擇的單個圖片:
     *   (1):獲得一個圖片的bitmap:
     *          調用相冊:PhoneUtils.getAlbumPhone(上下文環境);
     *          在onActivityResult()中PhoneUtils.onmyPhoneResult(this,requestCode,resultCode,data);獲得bitmap
     *   (2):獲得一個圖片的file:
     *          調用相冊:PhoneUtils.getAlbumPhone(上下文環境);
     *          在onActivityResult()中PhoneUtils.onmyPhoneFileResult(this,requestCode,resultCode,data);獲得file
     * 7.獲取拍照剪切圖片:
     *      調用PhoneUtils.getSheraPack(this,"cut.jpg");
     *      在在onActivityResult()中監聽PHONE_CODE_SHEAR_PACK響應碼調用Uri packUri =PhoneUtils.onInitCutPhoneResult(this,requestCode,resultCode,data,"cut.jpg");得到拍照的原圖
     *      在調用PhoneUtils.crop(this,packUri)進去截圖
     *      在在onActivityResult()中監聽PHONE_CODE__CUT截圖完畢響應碼  Bitmap photo=data.getParcelableExtra("data");
     *      得到phone這個截圖後的bitmap
     * 8.獲取相冊剪切圖片:
     *      調用PhoneUtils.getSheraMyPhone(this);進入相冊請求圖片
     *      在在onActivityResult()中監聽PHONE_CODE__SHEAR_MYPHONE響應碼調用Uri myUri=PhoneUtils.onCutmyPhoneResult(this,requestCode,resultCode,data);;得到相冊圖片uri
     *      在調用PhoneUtils.crop(this,myUri)進去截圖
     *      在在onActivityResult()中監聽PHONE_CODE__CUT截圖完畢響應碼  Bitmap photo=data.getParcelableExtra("data");
     *      得到phone這個截圖後的bitmap
     * 9.選擇相冊多張圖片:
     *
     */

    //拍照獲取縮略圖的請求碼
    public final static int PHONE_CODE_ABBPHONE=0;
    //拍照獲取相冊圖片的請求碼
    public final static int PHONE_CODE_ALBUNMPHONE=1;
    //拍照獲原圖圖的請求碼
    public final static int PHONE_CODE_INITPACKPHONE=2;
    //拍照剪切圖片請求碼
    public final static int PHONE_CODE_SHEAR_PACK=3;
    //相冊剪切圖片請求碼
    public final static int PHONE_CODE__SHEAR_MYPHONE=4;
    //剪切請求碼
    public final static int PHONE_CODE__CUT=5;

    /**
     * 調用系統相機獲取拍照縮略圖
     */
    public static void getAbbreviationsPhone(Activity activity){
        //爲安全起見,拿到sdcard是否可用的狀態碼
        String state = Environment.getExternalStorageState();
        //若是sd卡可用
        if (state.equals(Environment.MEDIA_MOUNTED)){ //若是可用
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            activity.startActivityForResult(intent,PHONE_CODE_ABBPHONE);
        }else {
            Toast.makeText(activity,"sdcard狀態異常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 調用系統相冊獲取獲取單張圖片uri
     */
    public static void getAlbumPhone(Activity activity){
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片類型  
        activity.startActivityForResult(intent,PHONE_CODE_ALBUNMPHONE);
    }

    /**
     * 調用相機獲取剪切圖
     */
    public static void getSheraPack(Activity activity,String fileName){
        //先驗證手機是否有sdcard 
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                //將拍攝的照片保存在一個指定好的文件下
                File dir= new File(Environment.getExternalStorageDirectory() + "/cut");
                if (!dir.exists()) dir.mkdirs();
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(dir, fileName);
                Uri u = Uri.fromFile(f);
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                activity.startActivityForResult(intent, PHONE_CODE_SHEAR_PACK);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(activity, "沒有找到儲存目錄", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(activity, "sdcard狀態異常", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 調用相冊獲取剪切圖
     */
    public static void getSheraMyPhone(Activity activity){
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片類型  
        activity.startActivityForResult(intent,PHONE_CODE__SHEAR_MYPHONE);
    }

    /**
     * 調用本地相機獲取拍照原圖
     * filename 圖片文件名 xxx.jpg
     * 返回值 圖片的路徑
     * 若是失敗返回空
     */
    public static void getInitPhone(Activity activity,String fileName) {
        //先驗證手機是否有sdcard 
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                //將拍攝的照片保存在一個指定好的文件下
                File dir= new File(Environment.getExternalStorageDirectory() + "/phone");
                if (!dir.exists()) dir.mkdirs();
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(dir, fileName);
                Uri u = Uri.fromFile(f);
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                activity.startActivityForResult(intent, PHONE_CODE_INITPACKPHONE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(activity, "沒有找到儲存目錄", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(activity, "sdcard狀態異常", Toast.LENGTH_LONG).show();
        }
    }

    /**
     *  onActivityResult拍照後返回原圖
     */
    public static  Bitmap onInitPhoneResult(Activity activity,int requestCode, int resultCode, Intent data,String fileName){
        try {
            File f=new File(Environment.getExternalStorageDirectory() + "/phone/"+fileName);
            Uri u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(activity.getContentResolver(), f.getAbsolutePath(), null, null));
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), u);
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  onActivityResult拍照後返回原圖Uri, 剪切經常使用
     */
    public static  Uri onInitCutPhoneResult(Activity activity,int requestCode, int resultCode, Intent data,String fileName){
        File f=new File(Environment.getExternalStorageDirectory() + "/cut/"+fileName);
        Uri u = null;
        try {
            u = Uri.parse(MediaStore.Images.Media.insertImage(activity.getContentResolver(), f.getAbsolutePath(), null, null));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return u;
    }

    /**
     *  onActivityResult拍照後返回縮略圖的bitmap
     */
    public static  Bitmap onAbbreviationsPhoneResult(Activity activity,int requestCode, int resultCode, Intent data){
        Bitmap phone = null;
        if (data.getData() != null|| data.getExtras() != null){
            Uri uri =data.getData();
            if (uri != null) {
                phone = BitmapFactory.decodeFile(uri.getPath());
                if (phone!=null){
                    return phone;
                }
            }
        }
        if (phone == null) {
            Bundle bundle =data.getExtras();
            if (bundle != null){
                phone =(Bitmap) bundle.get("data");
                if (phone!=null){
                    return phone;
                }
            } else {
                Toast.makeText(activity.getApplicationContext(), "找不到圖片",Toast.LENGTH_SHORT).show();
            }
        }
        return null;
    }

    /**
     *  onActivityResult相冊返回的bitmap
     */
    public static  Bitmap onmyPhoneResult(Activity activity,int requestCode, int resultCode, Intent data){
        Bitmap phone = null;
        Uri uri = data.getData();
        if (uri!=null){
            try {
                phone = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
                if (phone!=null){
                    return phone;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            Toast.makeText(activity.getApplicationContext(), "找不到該圖片",Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     *  onActivityResult相冊返回的uri  截圖多用
     */
    public static Uri onCutmyPhoneResult(Activity activity, int requestCode, int resultCode, Intent data){
        Bitmap phone = null;
        Uri uri = data.getData();
        if (uri!=null){
            return uri;
        }else {
            Toast.makeText(activity.getApplicationContext(), "找不到該圖片",Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     *  onActivityResult相冊返回的file
     */
    public static  File onmyPhoneFileResult(Activity activity,int requestCode, int resultCode, Intent data){
        Bitmap phone = null;
        Uri uri = data.getData();
        if (uri!=null){
            return uriToFile(activity,uri);
        }else {
            Toast.makeText(activity.getApplicationContext(), "找不到該圖片",Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     * 將bitmap保存到指定的文件路徑下
     * filepath:"/mnt/sdcard/pic/01.jpg"
     */
    public static void saveBitmapFile(Bitmap bitmap,String filePath){
        File file=new File(filePath);//將要保存圖片的路徑
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  將指定路徑下的圖片縮小到原來的幾分之一 返回bitmap.當inSampleSize=2時,表示縮小1/2
     */
    public static Bitmap getBitmapOption(String filePath,int inSampleSize){
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return BitmapFactory.decodeFile(filePath,options);
    }

    /**
     * uri轉file
     */
    public static  File uriToFile(Activity activity,Uri uri){
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = activity.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        File file = new File(data);
        return file;
    }

    /**
     * bitmap轉uri
     */
    public static Uri bitmapToUri(Activity activity,Bitmap bitmap){
        return  Uri.parse(MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap, null,null));
    }

    /**
     * uri轉bitmap
     */
    public static Bitmap bitmapToUri(Activity activity,Uri uri){
        Bitmap bitmap=null;
        try {
            bitmap= MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
        } catch (IOException e) {

        }
        return bitmap;
    }

    /**
     * 調用uCrop工具截圖
     * @param activity
     * @param uri
     */
    public static void startCrop(Activity activity,Uri uri){
        //裁剪後保存到文件中
        Uri sourceUri = uri;
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String imageName = simpleDateFormat.format(date);
        Uri destinationUri = Uri.fromFile(new File(activity.getCacheDir(), imageName+".jpeg"));
        UCrop.of(sourceUri, destinationUri).start(activity,PHONE_CODE__CUT);
    }

    /**
     * 保存圖片到相冊
     * @param context
     * @param bmp
     * @param saveAfterName 保存圖片的名稱須要帶後綴名
     */
    public static String saveImageToGallery(Context context, Bitmap bmp,String saveAfterName) {
        if (bmp == null){
            Toast.makeText(context,"圖片爲空,沒法保存!",Toast.LENGTH_SHORT).show();
            return null;
        }
        // 首先保存圖片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, saveAfterName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            Toast.makeText(context,"未發現文件!",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(context,"保存出錯!",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (Exception e){
            Toast.makeText(context,"保存出錯!",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        // 最後通知圖庫更新//註解掉改代碼,若是保留,則相冊會重複生成多個圖片
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), saveAfterName, null);
//        } catch (FileNotFoundException e){
//            e.printStackTrace();
//        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        return String.valueOf(file.getAbsoluteFile());
    }

    /**
     * 圖片轉換成Base64位字符串
     * @param file
     * @return
     */
    public static String photo2Base64String (File file){
        //將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
        String imgFile = file.getAbsolutePath();
        InputStream in = null;
        byte[] data = null;
        //讀取圖片字節數組
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return Base64.encodeToString(data, Base64.DEFAULT);//返回Base64編碼過的字節數組字符串
    }
}

調用相機和相冊的方法:java

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK)
        {
            switch(requestCode)
            {
                case PHONE_CODE_INITPACKPHONE:
                    //返回原圖
                    mPackBitmap=PhoneUtils.onInitPhoneResult(this,requestCode,resultCode,data,"init.jpg");
                    if (mPackBitmap!=null){
                       // mInitPachPhoneImageView.setImageBitmap(mPackBitmap);
                    }
                    break;
                case PHONE_CODE_ABBPHONE:
                    //返回縮略圖
                    Bitmap bitmap1 = PhoneUtils.onAbbreviationsPhoneResult(this, requestCode, resultCode, data);
                    if (bitmap1!=null){
                        //mFalsePhoneImageView.setImageBitmap(bitmap1);
                    }
                    break;
                case PHONE_CODE_ALBUNMPHONE:
                    //相冊圖片
                    Bitmap bitmap=PhoneUtils.onmyPhoneResult(this,requestCode,resultCode,data);
                    if (bitmap!=null){
                        //mMyPhoneImageView.setImageBitmap(bitmap);
                    }
                    break;
                case PHONE_CODE_SHEAR_PACK:
                    cutType=0;
                    //拍照截圖返回
                    //返回原圖
                    Uri packUri=PhoneUtils.onInitCutPhoneResult(this,requestCode,resultCode,data,"cut.jpg");
                    //進入截圖
                    Log.i("MAINACTVI","666");
                    PhoneUtils.startCrop(this,packUri);
                    Log.i("MAINACTVI","a");
                    break;
                case PHONE_CODE__SHEAR_MYPHONE:
                    cutType=1;
                    //相冊截圖返回
                    //返回相冊uri
                    Uri myUri=PhoneUtils.onCutmyPhoneResult(this,requestCode,resultCode,data);
                    //進入截圖
                    PhoneUtils.startCrop(this,myUri);
                    break;
                case PHONE_CODE__CUT:
                    Log.i("MAINACTVI","b");
                    //截圖完畢
                    Uri photoUri = UCrop.getOutput(data);
                    File newFile = PhoneUtils.uriToFile(OcrPhotoActivity.this,photoUri); //轉換爲File
                    newCompressedImageBitmap = Compressor.getDefault(this).compressToBitmap(newFile);//對圖片進行壓縮轉換爲Bitmap
                    if (cutType==0){
                        //拍照截圖
                        if(newCompressedImageBitmap!=null){
                          String imageViewId = (String) SharedPreferencesUtils.get(OcrPhotoActivity.this,"imageViewId","");
                            if (imageViewId.equals("1")){
                                ID_img_font.setImageBitmap(newCompressedImageBitmap);
                                SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_font",photoUri.toString());
                            }else if(imageViewId.equals("2")){
                                ID_img_back.setImageBitmap(newCompressedImageBitmap);
                                SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_back",photoUri.toString());
                            }else if(imageViewId.equals("3")){
                                ID_img_hand.setImageBitmap(newCompressedImageBitmap);
                                SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_hand",photoUri.toString());
                            }
                        }else{
                            Toast.makeText(this,"截圖錯誤",Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        //相冊截圖
                        if(newCompressedImageBitmap!=null){
                            String imageViewId = (String) SharedPreferencesUtils.get(OcrPhotoActivity.this,"imageViewId","");
                            if (imageViewId.equals("1")){
                                ID_img_font.setImageBitmap(newCompressedImageBitmap);
                                SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_font",photoUri.toString());
                            }else if(imageViewId.equals("2")){
                                ID_img_back.setImageBitmap(newCompressedImageBitmap);
                                SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_back",photoUri.toString());
                            }else if(imageViewId.equals("3")){
                                ID_img_hand.setImageBitmap(newCompressedImageBitmap);
                                SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_hand",photoUri.toString());
                            }
                        }else{
                            Toast.makeText(this,"截圖錯誤",Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }
    }

而後就是SharedPreferencesUtilsandroid

package www.tydic.com.util;

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * SharedPreferences的一個工具類,調用setParam就能保存String, Integer, Boolean, Float, Long類型的參數
 * 一樣調用getParam就能獲取到保存在手機裏面的數據
 * Created by LIUREN on 2017/2/16.
 */

public class SharedPreferencesUtils {
    public SharedPreferencesUtils()
    {
            /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }
    /**
     * 保存在手機裏面的文件名
     */
    private static final String FILE_NAME = "share_data";

    /**
     * 保存數據的方法,咱們須要拿到保存數據的具體類型,而後根據類型調用不一樣的保存方法
     *
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object){
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String)
        {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer)
        {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean)
        {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float)
        {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long)
        {
            editor.putLong(key, (Long) object);
        } else
        {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }
    /**
     * 獲得保存數據的方法,咱們根據默認值獲得保存的數據的具體類型,而後調用相對於的方法獲取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String)
        {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer)
        {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean)
        {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float)
        {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long)
        {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某個key值已經對應的值
     *
     * @param context
     * @param key
     */
    public static void remove(Context context, String key)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }
    /**
     * 清除全部數據
     *
     * @param context
     */
    public static void clear(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }
    /**
     * 查詢某個key是否已經存在
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }
    /**
     * 返回全部的鍵值對
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 建立一個解決SharedPreferencesCompat.apply方法的一個兼容類
     *
     * @author zhy
     *
     */
    private static class SharedPreferencesCompat
    {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        private static Method findApplyMethod()
        {
            try
            {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e)
            {
            }

            return null;
        }

        /**
         * 若是找到則使用apply執行,不然使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor)
        {
            try
            {
                if (sApplyMethod != null)
                {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e)
            {
            } catch (IllegalAccessException e)
            {
            } catch (InvocationTargetException e)
            {
            }
            editor.commit();
        }
    }
}

能夠把相關數據存儲到裏面,須要的時候獲取處理啊,如何存儲,如何獲取以下:數組

存儲:安全

SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_font","12345");

獲取:app

String ID_img_font_path = (String) SharedPreferencesUtils.get(OcrPhotoActivity.this,"ID_img_font","");
相關文章
相關標籤/搜索