从 Activity 到 Java Class 的共享首选项方法调用

Shared Preference Method Call From Activity to Java Class

所以我目前对 SharedPreferences 中的上下文有疑问,其中显示 LoginActivity.this。这是我的 device.java class,LoginActivity 是我想从中调用此方法的 Activity。那么它会像 Device.This 或类似的东西吗?

方法:

public void validateLogin(String username, String password, String ipAddress) {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

    if (sharedPreferences.contains("ip") && sharedPreferences.contains("username") && sharedPreferences.contains("password")) {
        String strUsername = sharedPreferences.getString("username", username);
        String strPassword = sharedPreferences.getString("password", password);
        String strIpAddress = sharedPreferences.getString("ip", ipAddress);
        //performLogin(strUsername, strPassword, strIpAddress);
    }
}

public void saveSP(String username, String password, String ipAddress) {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

    sharedPreferences.edit()
            .putString("ip", ipAddress)
            .putString("username", username)
            .putString("password", password)
            .commit();
}

试试这个:

public class MyActivity extends Activity{

    private static MyActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        activity = this;

        //...
    }

    public static MyActivity getActivity(){
        return activity;
    }

}

然后当您需要上下文对象时:

PreferenceManager.getDefaultSharedPreferences(MyActivity.getActivity());

当我需要 Activity class 之外的上下文对象时,这是我常用的方法。希望对您有所帮助!