2017-02-09 43 views
0

我想確保用戶在登錄後仍保持會話狀態,即使在用戶殺死應用程序後也是如此。用戶只有在他/她退出時才能結束會話。如何確保用戶即使在他/她殺了應用程序之後仍保持在會話中?

Login.java`

public class Login extends AppCompatActivity { 


EditText loginEmail, loginPassword; 
Button loginButton, registerButton; 
UserSessionManager session; 

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

    //User Session Manager 
    session = new UserSessionManager(getApplicationContext()); 
    loginEmail = (EditText) findViewById(R.id.login_email); 
    loginPassword = (EditText) findViewById(R.id.login_password); 
    loginButton = (Button) findViewById(R.id.login); 
    registerButton = (Button) findViewById(R.id.register); 

    Toast.makeText(getApplicationContext(), 
      "User Login Status: " + session.isUserLoggedIn(), 
      Toast.LENGTH_LONG).show(); 
} 
public void OnLogin(View view){ 
    String email = loginEmail.getText().toString(); 
    String password = loginPassword.getText().toString(); 
    String type = "login"; 
    BackgroundWorker backgroundWorker = new BackgroundWorker(this); 
    backgroundWorker.execute(type, email, password); 
    UserSessionManager userSessionManager = new UserSessionManager(this); 
    userSessionManager.createUserLoginSession(type, email); 
} 
public void OpenReg(View view){ 
    startActivity(new Intent(this, Register.class)); 
} 
} 

MainActivity.java

public class MainActivity extends AppCompatActivity { 

//User Session Manager 
UserSessionManager session; 

Button btnLogout; 

private static ImageButton profile_button1; 
private static TextView profile_button2; 
private static ImageButton link_button1; 
private static TextView link_button2; 

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

    //Session class instance 
    session = new UserSessionManager(getApplicationContext()); 
    TextView loginEmail = (TextView) findViewById(R.id.login_email); 
    TextView loginPassword = (TextView) findViewById(R.id.login_password); 

    //Logout 
    btnLogout = (Button) findViewById(R.id.btnLogout); 

    Toast.makeText(getApplicationContext(), "User Login Status: " + session.isUserLoggedIn(), 
    Toast.LENGTH_LONG).show(); 

    //check user login 
    if (session.checkLogin()) 
     finish(); 

    //get user data 
    HashMap<String, String> user = session.getUserDetails(); 

    //get email 
    String email = user.get(UserSessionManager.KEY_EMAIL); 

    btnLogout.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      session.logoutUser(); 
     } 
    }); 
} 

public void OnClickButtonListener() { 
    profile_button1 = (ImageButton) findViewById(R.id.ProfileButton); 
    profile_button2 = (TextView) findViewById(R.id.Profile); 
    link_button1 = (ImageButton) findViewById(R.id.LinkButton); 
    link_button2 = (TextView) findViewById(R.id.link); 

     profile_button1.setOnClickListener(
      new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Intent intent = new Intent("com.imedimate.imedimate.Profile"); 
        startActivity(intent); 
       } 
      } 
    ); 
     profile_button2.setOnClickListener(
      new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Intent intent = new Intent("com.imedimate.imedimate.Profile"); 
        startActivity(intent); 
       } 
      } 
    ); 
     link_button1.setOnClickListener(
      new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Uri uri = Uri.parse("http://www.imedimate.com"); // missing 'http://' will cause crashed 
        Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
        startActivity(intent); 
       } 
      } 
    ); 
     link_button2.setOnClickListener(
      new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        Uri uri = Uri.parse("http://www.imedimate.com"); // missing 'http://' will cause crashed 
        Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
        startActivity(intent); 
       } 
      } 
    ); 
} 
} 

UserSessionManager.java

public class UserSessionManager { 

//Shared preferences reference 
SharedPreferences pref; 

//Editor reference for shared preferences 
SharedPreferences.Editor editor; 

//Context 
Context _context; 

//shared pref mode 
int PRIVATE_MODE = 0; 

//sharedpref file name 
private static final String PREFER_NAME = "AndroidExamplePref"; 


//All Shared Preferences Keys 
private static final String IS_USER_LOGIN = "IsUserLoggedIn"; 

//email 
public static final String KEY_EMAIL = "email"; 

//constructor 
public UserSessionManager(Context context){ 
    this._context = context; 
    pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); 
    editor = pref.edit(); 
} 

//create login session 
public void createUserLoginSession(String name, String email){ 
    //store login value as TRUE 
    editor.putBoolean(IS_USER_LOGIN, true); 

    //store email in pref 
    editor.putString(KEY_EMAIL, email); 

    //commit changes 
    editor.commit(); 
} 

/** 
* check login method will check user status 
* If false it will redirect user to login page 
* Else do anything 
*/ 
public boolean checkLogin(){ 
//check login status 
if (!this.isUserLoggedIn()){ 
    //user is not logged in, redirected to login 
    Intent i = new Intent(_context, Login.class); 

    //closing all activities from stack 
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    //add new flag to start new activity 
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

    //staring login activity 
    _context.startActivity(i); 

    return true; 
} 
return false; 
} 
/** 
* Get stored session data 
*/ 
public HashMap<String, String> getUserDetails(){ 
    //Use hashmap to store user credentials 
    HashMap<String, String> user = new HashMap<String, String>(); 

    //user name 
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); 

    //return email 
    return user; 
} 
/** 
* Clear session details 
*/ 
public void logoutUser(){ 
    //clearing all user data from shared preferences 
    editor.clear(); 
    editor.commit(); 

    //After logout redirecr user to login 
    Intent i = new Intent(_context, Login.class); 

    //close all activities 
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    //add new flag to start new activity 
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

    //staring login 
    _context.startActivity(i); 
} 

//check for login 
public boolean isUserLoggedIn(){ 
    return pref.getBoolean(IS_USER_LOGIN, false); 
} 
} 

BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String,Void,String> { 
Context context; 
AlertDialog alertDialog; 
BackgroundWorker (Context ctx){ 
    context = ctx; 
} 
@Override 
protected String doInBackground(String... params) { 
    String type = params[0]; 
    String login_url = "http://imedimate.com/app/login.php"; 
    String register_url = "http://imedimate.com/app/register.php"; 
    if (type.equals("login")){ 
     try { 
      String email = params[1]; 
      String password = params[2]; 
      URL url = new URL(login_url); 
      HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); 
      httpURLConnection.setRequestMethod("POST"); 
      httpURLConnection.setDoOutput(true); 
      httpURLConnection.setDoInput(true); 
      OutputStream outputStream = httpURLConnection.getOutputStream(); 
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 
      String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&" 
        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8"); 
      bufferedWriter.write(post_data); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      outputStream.close(); 
      InputStream inputStream = httpURLConnection.getInputStream(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); 
      String result = ""; 
      String line = ""; 
      while ((line = bufferedReader.readLine()) != null) { 
       result += line; 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      httpURLConnection.disconnect(); 
      return result; 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } else if (type.equals("register")){ 
     try { 
      String regEmail = params[1]; 
      String regPassword = params[2]; 
      URL url = new URL(register_url); 
      HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); 
      httpURLConnection.setRequestMethod("POST"); 
      httpURLConnection.setDoOutput(true); 
      httpURLConnection.setDoInput(true); 
      OutputStream outputStream = httpURLConnection.getOutputStream(); 
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 
      String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&" 
        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8"); 
      bufferedWriter.write(post_data); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      outputStream.close(); 
      InputStream inputStream = httpURLConnection.getInputStream(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); 
      String result = ""; 
      String line = ""; 
      while ((line = bufferedReader.readLine()) != null) { 
       result += line; 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      httpURLConnection.disconnect(); 
      return result; 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return null; 
} 

@Override 
protected void onPreExecute() { 
    alertDialog = new AlertDialog.Builder(context).create(); 
    alertDialog.setTitle("Status"); 
} 

@Override 
protected void onPostExecute(String result) { 
    alertDialog.setMessage(result); 
    if (result.contains("success")) { 
     Intent intent = new Intent(context, MainActivity.class); 
     context.startActivity(intent); 
    } else { 
     alertDialog.show(); 
    } 
} 

@Override 
protected void onProgressUpdate(Void... values) { 
    super.onProgressUpdate(values); 
} 
} 

回答

0

這是不可能的。

您可以做的最好的事情是確保在應用程序死亡後,儘快創建(粘滯)Service,這可以設置一個新的會話。如果您需要來自應用用戶的某種認證,情況會變得更加複雜。優先

0
  1. 存儲用戶會話令牌在登錄成功
  2. 在發射活動檢查會話令牌。如果存在令牌,則啓動主屏幕(主屏幕)。
  3. 在註銷時從首選項中刪除令牌。
相關問題