Я считаю, что все сообщения выше, но я хотел добавить свои два цента. Когда приложение запускается, вы должны сделать звонок в вашей Launcher Activity
(деятельность, которая запускает, когда ваш значок приложения щелкнуть на главном экране, если он еще не открыт) для
// This will get you an instance of your applications shared preferences.
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPrefs", SharedPreferences.MODE_PRIVATE);
// Values
String userName = preferences.getString("username",null);
String password = preferences.getString("password",null);
// Then you want to query preferences for values such as username and password like
if((userName != null) && (password != null))
{
// **** Log your user into your application auto**Magically** ********
// ------------------- Option 1 - web request -------------------
// First i Would make the initial Web Request before trying to send my User into
// a new Activity.
// Run an `AsynchTask` against your webservice on the server if this is something
// you need to do to see if the username and password, are correct and registered
//---------- Option 2 - Check the SQLite Database(if you are using one) ---------
// Otherwise you can use this info to read from an SQLiteDatabase on your device.
// To see if they are registered
// This is where you would create a new intent to start
// and Login your user, so that when your application is launched
// it will check if there are a username and password associated to the
// Application, if there is and these are not null do something like
// Create a new Intent
Intent automagicLoginIntent = new Intent(getBaseContext(),AutomagicLogin.class);
// Pass the Bundle to the New Activity, if you need to reuse them to make additional calls
Bundle args = new Bundle();
args.putString("username", userName);
args.putString("password", password);
automagicLoginIntent.putExtra("UserInfo", args);
// Launch the Activity
startActivity(automagicLoginIntent);
}else{
// Show the Layout for the current Activity
}
Это должно быть сделано в методе onCreate(Bundle savedInstanceState);
но это за исключением этого. Это не должно быть слишком сложным для реализации, но реализация зависит от того, как работает ваша логика.
Вы прочитали из базы данных SQLIte? Вы читаете из WebService?
т.д.
Но это должно быть все, что вам нужно, если вам не нужно хранить некоторые другие значения в префов.
Side Примечание
Все выше код не будет работать, если у вас нет никакой возможности получать эту информацию от пользователя, в первую очередь, то есть форма регистрации.
Когда вы думаете о регистрации, вы можете сначала сохранить эти значения с помощью следующего кода:
// Inside an Listener , get a reference to your `TextView`s that were used to enter
// username and password
TextView usernameText = (TextView) findViewById(R.id.textViewUsername);
TextView passwordText = (TextView) findViewById(R.id.textViewPassword);
// Get a reference to the SharedPReferences, SO WE CAN BEGIN TO STORE THE VALUES ENTERED
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPrefs", SharedPreferences.MODE_PRIVATE);
// Need this to Edit Preferences
SharedPreferences.Editor editor = preferences.edit();
// Then you can add the values
editor.putString("username",usernameText.getText().toString().trim());
editor.putString("password",passwordText.getText().toString().trim());
// Must Call this to write values to the Preferences
editor.commit();
И это должно быть все, что вам нужно, чтобы сначала сохранить значения и читать их от предпочтений автомагический войти в вашем каждый раз, когда приложение ur запускается, если оно не было открыто, если он был открыт, жизненный цикл активности Android должен перезагрузить текущую приостановленную деятельность.
Удачи!
Проверить общие сведения – Merlevede
Возможный дубликат [Android: Сохранение имени пользователя и пароля?] (Http://stackoverflow.com/questions/1925486/android-storing-username-and-password) –