创建共享首选项方法并将其从活动移动到 Java



我对Android Studio还很陌生,我想让我的共享首选项成为我的设备.java类中的一个方法,以便它正确验证。但是,我不确定应该初始化哪些变量以及代码放置。我的共享首选项代码的作用是验证用户是否是同一用户并执行登录以绕过登录屏幕,即第一次需要登录,终身绕过欢迎屏幕。

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 static void login(String username, String password, String ipAddress, final Callback callback) throws JSONException {
    OkHttpClient client = new OkHttpClient();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("username", username);
    jsonObject.put("password", password);
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
    Request request = new Request.Builder()
            .url("http://"+ipAddress+"/api/v0/login")
            .post(body)
            .build();
    client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {

        // produces exception if db connection request has fail
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onLoginFailure(e);
        }
        // checks is db request passed or fail
        @Override public void onResponse(Response response){
            if (!response.isSuccessful()) {
                callback.onLoginFailure(new IOException("Unexpected code " + response));
                return;
            }
            String jsonAsString = null;
            try {
                jsonAsString = response.body().string();
                JSONObject json = new JSONObject(jsonAsString);
                if (json.getString("status").equals("ok")){
                    Device device = new Device();
                    device.locationID = json.getInt("location_id");
                    //device.imageID = json.getInt("imageId");
                   // device.imageName = json.getString("imageName");
                    device.id = json.getInt("id");
                    Device.instance = device;
                    callback.onLoginSuccess(device);
                } else {
                    throw new JSONException("Invalid service response");
                }
            } catch (Exception e) {
                e.printStackTrace();
                callback.onLoginFailure(e);
            }
        }
    });
}

Device.java中,您可以添加如下内容:

public class Device {
    private final SharedPreferences preferences;
    public Device(Context context) {
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
    }
    public void validateLogin(String username, String password, String ipAdress) {        
        if (preferences.contains("ip") && preferences.contains("username") && preferences.contains("password")) {
            String strUsername = preferences.getString("username", username);
            String strPassword = preferences.getString("password", password);
            String strIpAddress = preferences.getString("ip", ipAddress);
            performLogin(strUsername, strPassword,strIpAddress);
        }
    }
// Your code...
}
然后,您可以从

LoginActivity致电:

Device device = new Device(this);
device.validateLogin();

最新更新