首先是歡迎界面的代碼
public class WelcomeActivity extends Activity{
? ? @Override
? ? protected void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.welcome);
? ? ? ? /**
? ? ? ? * 延遲3秒進入主界面
? ? ? ? */
? ? ? ? new Handler().postDelayed(new Runnable() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? Intent intent=new Intent(WelcomeActivity.this,LoginActivity.class);
? ? ? ? ? ? ? ? startActivity(intent);
? ? ? ? ? ? ? ? WelcomeActivity.this.finish();
? ? ? ? ? ? }
? ? ? ? },1000*3);
? ? }
}
接下來是文章的主要內容。實現(xiàn)自動登錄的關鍵是當程序從歡迎界面跳轉到登錄界面是,在登錄界面還沒有加載布局文件時判斷是否登陸過畏妖,從而實現(xiàn)直接跳轉到主界面亲澡。這里我們采用SharedPreferences來保存登錄狀態(tài)。代碼如下:
public class LoginActivity extends Activity{
? ? SharedPreferences sprfMain;
? ? SharedPreferences.Editor editorMain;
? ? Button login;
? ? @Override
? ? protected void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? //在加載布局文件前判斷是否登陸過
? ? ? ? sprfMain= PreferenceManager.getDefaultSharedPreferences(this);
? ? ? ? editorMain=sprfMain.edit();
? ? ? ? //.getBoolean("main",false)耗啦;當找不到"main"所對應的鍵值是默認返回false
? ? ? ? if(sprfMain.getBoolean("main",false)){
? ? ? ? ? ? Intent intent=new Intent(LoginActivity.this,MainActivity.class);
? ? ? ? ? ? startActivity(intent);
? ? ? ? ? ? LoginActivity.this.finish();
? ? ? ? }
? ? ? ? setContentView(R.layout.login);
? ? ? ? login= (Button) findViewById(R.id.login);
? ? ? ? //這里只是簡單用按鍵模擬登錄功能
? ? ? ? login.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? Intent intent=new Intent(LoginActivity.this,MainActivity.class);
? ? ? ? ? ? ? ? editorMain.putBoolean("main",true);
? ? ? ? ? ? ? ? editorMain.commit();
? ? ? ? ? ? ? ? startActivity(intent);
? ? ? ? ? ? ? ? LoginActivity.this.finish();
? ? ? ? ? ? }
? ? ? ? });
? ? }
}
接下來是實現(xiàn)注銷后要重新進入登錄界面
public class MainActivity extends AppCompatActivity {
? ? SharedPreferences sprfMain;
? ? SharedPreferences.Editor editorMain;
? ? Button exit;
? ? @Override
? ? protected void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.activity_main);
? ? ? ? exit= (Button) findViewById(R.id.exit);
? ? ? ? exit.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? //點擊注銷按鍵后調用LoginActivity提供的resetSprfMain()方法執(zhí)行editorMain.putBoolean("main",false);凿菩,即將"main"對應的值修改為false
? ? ? ? ? ? ? ? resetSprfMain();
? ? ? ? ? ? ? ? Intent intent=new Intent(MainActivity.this,WelcomeActivity.class);
? ? ? ? ? ? ? ? startActivity(intent);
? ? ? ? ? ? ? ? MainActivity.this.finish();
? ? ? ? ? ? }
? ? ? ? });
? ? }
? ? public void resetSprfMain(){
? ? ? ? sprfMain= PreferenceManager.getDefaultSharedPreferences(this);
? ? ? ? editorMain=sprfMain.edit();
? ? ? ? editorMain.putBoolean("main",false);
? ? ? ? editorMain.commit();
? ? }
}