首先,我是 Android 的新手,对任何不合理的事情表示歉意。
我在这里要做的是显示主要活动并显示一个 AlertDialog,要求输入短密码(完整的用户名和密码将保存在首选项中)。如果密码不匹配,我需要找到退出应用程序的方法,否则,加载主要活动。
到目前为止,这是我的代码:
public class MainActivity extends Activity implements OnClickListener
{
Button screening;
Button screeningLog;
@Override
protected void onCreate (Bundle savedInstanceState)
{
resetPreferences ();
// Set theme
setTheme (App.getTheme ());
setContentView (R.layout.main);
super.onCreate (savedInstanceState);
createControlsAndListeners ();
if (!App.isLoggedIn ())
{
final LinearLayout view = new LinearLayout (this);
final TextView passcodeText = new TextView (this);
final EditText passcode = new EditText (this);
passcodeText.setText (R.string.passcode);
passcode.setHint (R.string.passcode_hint);
passcode.setInputType (InputType.TYPE_TEXT_VARIATION_PASSWORD);
view.setOrientation (LinearLayout.VERTICAL);
view.addView (passcodeText);
view.addView (passcode);
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.setTitle ("Enter Passcode.");
builder.setView (view);
builder.setPositiveButton (R.string.login, new DialogInterface.OnClickListener ()
{
public void onClick (DialogInterface dialog, int whichButton)
{
if (App.get (passcode).equals (App.getPassword ().substring (0, 4)))
{
App.setLoggedIn (true);
dialog.dismiss ();
}
else
{
Toast toast = Toast.makeText (MainActivity.this, Error.get (Error.AUTHENTICATION),
App.getDelay ());
toast.show ();
}
}
});
builder.show ();
}
}
public void resetPreferences ()
{
PreferenceManager.setDefaultValues (this, R.xml.preferences, false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences (this);
App.setServer (preferences.getString ("server", ""));
App.setUsername (preferences.getString ("username", ""));
App.setPassword (preferences.getString ("password", ""));
App.setNightMode (preferences.getBoolean ("night_mode", false));
App.setDelay (Integer.parseInt (preferences.getString ("delay", "30000")));
}
private void createControlsAndListeners ()
{
screening = (Button) findViewById (R.main_id.screeningButton);
screening.setOnClickListener (this);
screeningLog = (Button) findViewById (R.main_id.screeningLogButton);
screening.setOnClickListener (this);
}
}