安卓 SharedPreferences(功能:实现记住密码)

一.SharedPreferences

2.如何存储数据

步骤1:得到SharedPreferences对象 getSharedPreferences(“文件的名称”,“文件的类型”);
(1).Context.MODE_PRIVATE:指定该SharedPreferences数据只能被应用程序读写
(2).Context.MODE_WORLD_READABLE:指定该SharedPreferences数据能被其他应用程序读,但不能写。
(3).Context,MODE_WORLD_WRITEABLE:指定该SharedPreferences数据能被其他应用程序写,但不能读。
步骤2:得到 SharedPreferences.Editor编辑对象
SharedPreferences.Editor editor=sp.edit();
步骤3:添加数据
editor.putBoolean(key,value)
editor.putString()
editor.putInt()
editor.putFloat()
editor.putLong()
步骤4:提交数据 editor.commit()
//写数据 代码如下

// An highlighted block
public  void write(){
    SharedPreferences  preferences = getSharedPreferences("yangzhibin",MODE_PRIVATE);

    SharedPreferences.Editor edit = preferences.edit();

    edit.putString("message","AAbcdea22dferwplkCC321ou1");

    edit.commit();
}

3.如何读取数据
步骤1:得到SharedPreferences对象 getSharedPreferences(“文件的名称”,“文件的类型”);

步骤2:读取数据 String msg = sp.getString(key,defValue);
//读数据 代码如下

// An highlighted block
SharedPreferences  preferences = getSharedPreferences("yangzhibin",MODE_PRIVATE);

String message = preferences.getString("message", "");

二.文件存储:内部文件存储+外部文件存储(SD卡)(******)
1.一般手机文件管理 根路径 /storage/emulated/0/或者/mnt/shell/emulated/0
在这里插入图片描述
2.重要代码:
(1)Environment.getExternalStorageState();// 判断SD卡是否
(2)Environment.getExternalStorageDirectory(); 获取SD卡的根目录
(3)Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 获取SD卡公开目录pictures文件夹

3.必须要添加读写SD卡的权限

// An highlighted block
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

读写json字符串
向sdk写入数据 代码如下:

// An highlighted block
private void write_json(String message) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        File path = Environment.getExternalStorageDirectory();
        File file1 = new File(path,"1702C//杨智斌");
        if (!file1.exists()){
            file1.mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(file1,"readTwo.txt"));
            fos.write(message.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

从sdk读取数据 代码如下:

    public static String read_json() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = Environment.getExternalStorageDirectory();
            FileInputStream is= null;
            StringBuffer sb=new StringBuffer();
            try {
                inputStream=new FileInputStream(new File(file,"readTwo.txt"));
                byte[] b=new byte[1024];
                int len=0;
                while((len=is.read(b))!=-1){
                    sb.append(new String(b,0,len));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return  sb.toString();
        }else{
            return "";
        }
    }

## 三级缓存
1.内存工具类

```javascript
// An highlighted block
public class LruUtils {

        private LruCache<String, Bitmap> lruCache;
        private Long max = Runtime.getRuntime().maxMemory();//获得手机的最大内容

        public LruUtils(){
            lruCache = new LruCache<String, Bitmap>((int) (max/8)){
                @Override
                protected int sizeOf(String key, Bitmap value) {
                    return value.getByteCount();
                }
            };
        }

    public Bitmap getBitmap(String key){
            return  lruCache.get(key);
    }

    public void  setBitamap(String key,Bitmap bitmap){
            lruCache.put(key,bitmap);
    }

}

2.sdk工具类

public class SDKutils {
    //存图片
    public  Bitmap getBitmap(String name){
        //获取图片路径
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file =  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File file1 = new File(file,name);

            return  BitmapFactory.decodeFile(file1.getAbsolutePath());
        }
        return null;
    }

    //读图片
    public   void setBitmap(String name,Bitmap bitmap){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file = Environment.getExternalStoragePublicDirectory(Environment.MEDIA_BAD_REMOVAL);
            File file1 = new File(file,name);

            try {
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file1));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}

3.网络请求工具类

public class HttpTools {

    public  static Bitmap getBitmap(String URL) throws ExecutionException, InterruptedException {
      return new MyTask().execute(URL).get();
    }

    static class MyTask extends AsyncTask<String,String,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... strings) {

            String imageUrl = strings[0];
            HttpURLConnection httpURLConnection = null;

            try {
                URL url = new URL(imageUrl);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.connect();
                if (httpURLConnection.getResponseCode() == 200){
                    InputStream is = httpURLConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    return  bitmap;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (httpURLConnection!=null){
                        httpURLConnection.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }



}

4.使用3个工具类,实现三级缓存

// An highlighted block
public class SendActivity extends AppCompatActivity {
    Button button;
    ImageView imageView;
    LruUtils lruUtils = new LruUtils();
    HttpToos httpToos = new HttpToos();
    SDKutils sdKutils = new SDKutils();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);

        button = findViewById(R.id.buttonone);
        imageView = findViewById(R.id.imagetwo);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Cache_images();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public  void  Cache_images() throws ExecutionException, InterruptedException {
        Bitmap bitmap = lruUtils.getBitmap("背景");
        if (bitmap!=null){
            imageView.setImageBitmap(bitmap);
            Toast.makeText(this, "图片来自缓存中", Toast.LENGTH_SHORT).show();
        }else{
            bitmap = sdKutils.getBitmap("背景.jpg");
            if (bitmap!=null){
                imageView.setImageBitmap(bitmap);
                new LruUtils().setBitamap("背景",bitmap);
                Toast.makeText(this, "图片来自Sdk中", Toast.LENGTH_SHORT).show();
            }else{
                bitmap = httpToos.getBitmap("http://img02.tooopen.com/images/20150507/tooopen_sy_122395947985.jpg");
                if (bitmap!=null){
                    imageView.setImageBitmap(bitmap);
                    lruUtils.setBitamap("背景",bitmap);
                    sdKutils.setBitmap("背景.jpg",bitmap);
                    Toast.makeText(this, "图片从网络上获取", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值