I want to implement login screen in my app and looking for the best practice. Suppose this code:
public class LoginActivity extends Activity {
public void onCreate(Bundle icicle){
super.onCreate(icicle);
setContentView(R.layout.activity_login);
Button btnLogin=(Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}
public class MainActivity extends Activity {
public void onCreate(Bundle icicle){
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnLogout=(Button)findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".LoginActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
That's will work for the first app run, I will remember password. But next time, when password already exists in app storage, I don't want to show LoginActivity. So, the only solution I have:
public class LoginActivity extends Activity {
public void onCreate(Bundle icicle){
super.onCreate(icicle);
setContentView(R.layout.activity_login);
Button btnLogin=(Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
//consider that passwodExists() looks for credentials
if(passwodExists()){
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
}
}
Is that acceptable?
- What would you use for such problem?
- Is that safe to start Activity or show dialog from onCreate()?
I think that's OK as long as you take into consideration the back button in the main layouts onResume() and close the application if there isn't a valid login.
When I did this I made a splash screen type activity that determined to go to the Login activity or to the Main activity and made sure that the splash screen activity was not part of the back task history. That way when then hit the back button on the login activity, it would finish off the application.