在保持同一会话的同时打开仪表板

时间:2017-07-19 06:57:09

标签: android session login sharedpreferences back-button

我能够登录系统,并从系统退出。当我从仪表板按回而不从系统登出。我每次都登录系统。如何在不进行登出的情况下限制登录页面来自System.I需要打开Dashbord页面,如果用户没有从系统注销并在访问时间到期时直接登录到

登录

public class Login extends AppCompatActivity implements View.OnClickListener {

    EditText userName, Password;
    Button login;
    public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
    public static final String KEY_USERNAME = "UserName";
    public static final String KEY_PASSWORD = "Password";
    String username, password;
    String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires, masterid1;

    SessionManagement sessionManagement;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        userName = (EditText) findViewById(R.id.login_name);
        Password = (EditText) findViewById(R.id.login_password);
        userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
        Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(this);

   /*     sessionManagement = (SessionManagement) getSharedPreferences("mySharedPref", 0);
        if (sessionManagement.isLoggedIn()) {

            startActivity(new Intent(getApplicationContext(), Home.class));

        }    */

    }


    private void UserLogin() {

        username = userName.getText().toString().trim();
        password = Password.getText().toString().trim();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            accesstoken = jsonObject.getString("access_token");
                            tokentype = jsonObject.getString("token_type");
                            expiresin = jsonObject.getString("expires_in");
                            username = jsonObject.getString("userName");
                            masterid = jsonObject.getString("MasterID");
                            masterid = masterid.replaceAll("[^\\.0123456789]", "");

                            masterid1 = jsonObject.getString("MasterID");

                            name = jsonObject.getString("Name");
                            access = jsonObject.getString("Access");
                            issue = jsonObject.getString(".issued");
                            expires = jsonObject.getString(".expires");
                            SessionManagement session = new SessionManagement(Login.this);
                            session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
                            // session.createLoginSession(masterid1);
                            openProfile();

                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(Login.this, "Please enter valid username and Password", Toast.LENGTH_SHORT).show();
                    }
                }) {


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                //params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
                return params;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_USERNAME, username);
                map.put(KEY_PASSWORD, password);
                //map.put("access_token", accesstoken);
                map.put("grant_type", "password");
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }


    private void openProfile() {
        Intent intent = new Intent(this, Home.class);
        intent.putExtra(KEY_USERNAME, username);
        startActivity(intent);
        startActivity(intent);

    }

    @Override
    public void onClick(View v) {
        UserLogin();
    }


}

SessionManagement 用于存储访问令牌和其他所需信息

public class SessionManagement {

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;
    // Shared pref mode
    int PRIVATE_MODE = 0;
    // Sharedpref file name
    private static final String PREF_NAME = "AndroidHivePref";
    private static final String IS_LOGIN = "IsLoggedIn";
    public static final String KEY_access_token = "access_token";
    public static final String KEY_token_type = "token_type";
    public static final String Key_EXPIRES_IN = "expires_in";
    public static final String KEY_USERNAME = "userName";
    public static final String KEY_MASTER_ID = "MasterID";
    public static final String KEY_MASTER_ID1 = "MasterID";

    public static final String KEY_Name = "Name";
    public static final String KEY_Access = "Access";
    public static final String KEY_Issued = ".issued";
    public static final String KEY_expires = ".expires";


    // Constructor
    public SessionManagement(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    SettingFragment context;


    public void createLoginSession(String accesstoken, String tokentype, String expiresin, String username, String masterId, String name, String access, String issued, String expires) {

        editor.putBoolean(IS_LOGIN, true);
        editor.putString(KEY_access_token, accesstoken);
        editor.putString(KEY_token_type, tokentype);
        editor.putString(Key_EXPIRES_IN, expiresin);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_MASTER_ID, masterId);
        editor.putString(KEY_MASTER_ID1, masterId);
        editor.putString(KEY_Name, name);
        editor.putString(KEY_Access, access);
        editor.putString(KEY_Issued, issued);
        editor.putString(KEY_expires, expires);
        editor.apply();

        String user_new_access_token = pref.getString(KEY_access_token, null);
        String user_new_access_tokentype = pref.getString(KEY_token_type, null);
        String user_name_expiresin = pref.getString(Key_EXPIRES_IN, null);
        String user_name_Username = pref.getString(KEY_USERNAME, null);
        String user_name_masterID = pref.getString(KEY_MASTER_ID, null);
        String user_name_name = pref.getString(KEY_Name, null);
        String user_name_access = pref.getString(KEY_Access, null);
        String user_name_issued = pref.getString(KEY_Issued, null);
        String user_name_expires = pref.getString(KEY_expires, null);
        String user_name_masterID1 = pref.getString(KEY_MASTER_ID1, null);


        Log.d("TAG", "Access Token :" + accesstoken + user_new_access_token);
        Log.d("TAG", "TokenType:" + user_new_access_tokentype);
        Log.d("TAG", "Expires in:" + user_name_expiresin);
        Log.d("TAG", "UserName:" + user_name_Username);
        Log.d("TAG", "MasterID:" + user_name_masterID);

        Log.d("TAG", "Name:" + user_name_name);
        Log.d("TAG", "Access:" + user_name_access);
        Log.d("TAG", "Issued:" + user_name_issued);
        Log.d("TAG", "Expires:" + user_name_expires);

        Log.d("TAG", "user_name_masterID1:" + user_name_masterID1);

        //  String user_name_new = pref.getString(KEY_access_token, null);

        //  Log.d("TAG", " :" + accesstoken + " user_name_new:" + user_name_new);


        //  Log.d(tokentype, "admin");
        //ad Log.d(expiresin, "expiresin");

        editor.commit();


    }


    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     */
    public void checkLogin() {
        // Check login status
        if (!this.isLoggedIn()) {
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, Login.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

    }


    /**
     * Get stored session data
     */
    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        //  user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null));
        user.put(KEY_access_token, pref.getString(KEY_access_token, null));
        user.put(KEY_token_type, pref.getString(KEY_token_type, null));
        //  user.put(KEY_TOKEN_TYPE, pref.getString(KEY_TOKEN_TYPE, null));
        // user.put(KEY_MASTER_ID, pref.getString(KEY_MASTER_ID, null));
        // user.put(KEY_access_token, pref.getString(KEY_access_token, null));
        // user.put(KEY_NAME, pref.getString(KEY_NAME, null));
        //user.put(KEY_Access, pref.getString(KEY_Access, null));


        // return user
        return user;
    }

    /**
     * Clear session details
     */
    public void logoutUser() {

        editor.clear();
        editor.commit();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, Login.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }


    public String getMasterId() {
        String masterID = pref.getString(KEY_MASTER_ID, null);
        return masterID;
    }


    public String getMasterId1() {
        String masterID = pref.getString(KEY_MASTER_ID1, null);
        return masterID;
    }

    public String getAccess() {
        String accessID = pref.getString(KEY_Access, null);
        return accessID;
    }

    public String getKeyName() {
        String KeyName = pref.getString(KEY_Name, null);
        return KeyName;
    }


    public String getAccesstToken() {
        String user_new_access_token = pref.getString(KEY_access_token, null);
        return user_new_access_token;
    }


    public void clear() {
        Log.d("TAg", "Full Cleared");
        editor.clear();

        // editor.remove(KEY_MASTER_ID);
        // editor.remove(KEY_USERNAME);
        editor.commit();


    }


    /**
     * Quick check for login
     **/
    // Get Login State
    public boolean isLoggedIn() {
        return pref.getBoolean(IS_LOGIN, false);
    }


}
  

如果用户没有退出,我如何指向仪表板页面   系统

1 个答案:

答案 0 :(得分:1)

我已经在登录页面上检查了会话。如果 isLoggedIn()== true ,那么我已切换到仪表板页面。

<强> sessionmanagement

  public boolean isLoggedIn() {
        System.out.println("Pref" + pref.getBoolean(IS_LOGIN, false));
        return pref.getBoolean(IS_LOGIN, false);
    }

 public boolean checkLogin() {
        // Check login status


        if (!this.isLoggedIn()) {
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, Login.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity



            _context.startActivity(i);

        }

       // return false;
        return false;
    }

<强>登录

if (session.isLoggedIn() == true) {
        Intent intent = new Intent(this, Home.class);
        startActivity(intent);
    }
  

也可以检查会话到期时间