SharedPreferences util工具类封装

来源:互联网 发布:怎么避免淘宝找相似 编辑:程序博客网 时间:2024/05/17 08:41
package com.bwei.ds.util;

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

/**
 * Created by MK on 2017/11/14.
 */
public class SharedUtil {
    private static SharedPreferences preferences;
    public static void setData(Context context, String key, boolean value){
        if (preferences==null){
            preferences = context.getSharedPreferences("config", Context.MODE_APPEND);
        }
        //存值
        preferences.edit().putBoolean(key,value).commit();
    }
    public static boolean getData(Context context,String key,boolean value){
        if (preferences==null){
            preferences = context.getSharedPreferences("config", Context.MODE_APPEND);
        }
        //取值
        boolean b = preferences.getBoolean(key, value);
        return b;
    }
}



package com.bwei.ds;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.bwei.ds.util.SharedUtil;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private int time = 5;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                if (time>0){
                    time--;
                    textView.setText(time+"秒");
                    handler.sendEmptyMessageDelayed(0,1000);
                }else{
                    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text_id);
        boolean flag = SharedUtil.getData(MainActivity.this, "flag", false);
        if (flag){
            Intent intent = new Intent(MainActivity.this,SecondActivity.class);
            startActivity(intent);
            finish();
        }else {
            SharedUtil.setData(MainActivity.this,"flag",true);
            handler.sendEmptyMessageDelayed(0,1000);
        }
    }
}