共享首选项适用于棒棒糖和棉花糖,但不适用于kitkat

时间:2016-12-29 15:39:04

标签: android sharedpreferences

当我杀死应用程序共享首选项键值正在删除时,我在共享首选项中添加了令牌值,当我在Lolipop中运行时,它很好但不能在kitkat中运行,我尝试了很多但没有得到令人满意的结果。

SplashActivity.java

public class SplashActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    String authToken = new DevicePreferences().getString(SplashActivity.this, Global_Variables.AUTH_TOKEN, "");

    if (new DevicePreferences().getString(SplashActivity.this, Global_Variables.AUTH_TOKEN, "").equalsIgnoreCase("")) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashActivity.this, WelcomeActivity.class);
                startActivity(i);
                finish();
            }
        }, 3000);
    } else {
        Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
        startActivity(intent);
        finish();
    }
}
}

DevicePreferences.java

public class DevicePreferences {

public SharedPreferences get(Context context) {
    return context.getSharedPreferences(Global_Variables.PREF_FILE_NAME, Context.MODE_PRIVATE);
}

public void addKey(Context context, String key, String value) {
    SharedPreferences settings = get(context);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);
    editor.commit();
}

public String getString(Context context, String key, String defValue) {
    SharedPreferences prefs = get(context);
    return prefs.getString(key, defValue);
}
}

Global_Variables.java

public class Global_Variables  {
public static final String PREF_FILE_NAME = "GFresh";
public static String AUTH_TOKEN = "auth_token";
}

0 个答案:

没有答案