2017-03-01 57 views
3

我想注销和会话Android应用程序的终止虚假不使用Android应用的注销按钮注销和会话在Android应用程序的终止虚假不使用注销按钮

终止时没有点击的用户在注销按钮,我想注销并终止当前会话。这怎么能做到呢?

这是我的会话类

public class Session { 
    SharedPreferences preferences; 
    SharedPreferences.Editor editor; 
    Context ctx; 

    public Session(Context ctx) { 
     this.ctx = ctx; 
     preferences = ctx.getSharedPreferences("Novel Traveller",Context.MODE_PRIVATE); 
     editor =preferences.edit(); 
    } 

    public void setLoggedin(boolean loggedin){ 
     editor.putBoolean("Logged In mode",loggedin); 
     editor.commit(); 

    } 

    public boolean loggedIn(){ 
     return preferences.getBoolean("Logged In mode",false); 
    } 
} 

这是主要活动

enter code here 

    public class MainActivity extends AppCompatActivity { 
    private Button btnLogout; 
    private Session session; 

    public static final String NOTE_ID_EXTAR = "com.text.traveller.novel_traveller_application.Note Identifier"; 
    public static final String NOTE_TITLE_EXTAR = "com.text.traveller.novel_traveller_application.Note Title"; 
    public static final String NOTE_MESSAGE_EXTAR = "com.text.traveller.novel_traveller_application.Note Message"; 
    public static final String NOTE_CATEGORY_EXTAR = "com.text.traveller.novel_traveller_application.Note Category"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     btnLogout =(Button)findViewById(R.id.btnLogout); 
     session = new Session(this); 
     if(!session.loggedIn()){ 
      logout(); 
     } 
     btnLogout = (Button)findViewById(R.id.btnLogout); 
     btnLogout.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       logout(); 
      } 
     }); 
    } 
    private void logout(){ 
     session.setLoggedin(false); 
     finish(); 
     startActivity(new Intent(MainActivity.this,loginActivity.class)); 
    } 
} 

回答

1

建立在你我的会话类像注销方法:

public void logout() { 
     SharedPreferences.Editor editor = getSharedPreferences().edit(); 
     editor.clear(); 
     editor.apply(); 
    } 

和覆盖的onStop( )方法在你的活动,只写:

@Override 
protected void onStop() { 
super.onStop(); 
session.setLoggedin(false); 
session.logout(); 
} 
+0

谢谢,我会试试这个 –