私はAndroid用のビルドとアプリケーションです。私はアプリを閉じた後でもユーザーをログインさせ続けるつもりです。私はそれに対処するためにはSessionManagerと呼ばれるこのクラスを使用しています:ログインアクティビティでオープンできないアクティビティ - Androidのセッションマネージャー
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
私は、このコード行を追加:
SessionManager session;
session = new SessionManager(getApplicationContext());
そして、入力した資格情報がに保存されているものと比較された後にデータベース私はこれを行う:
session.createLoginSession("Username", "email_address");
これは、ユーザーがログインしている場合、私は1をオープンするように設定する画面です:
public class MainScreen extends AppCompatActivity {
Switch list_toggle;
String user_id,username,status;
boolean ischecked;
public static String Name;
SessionManager session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
session = new SessionManager(getApplicationContext());
session.checkLogin();
final TextView textView4 = (TextView) findViewById(R.id.textView4);
final TextView textView3 = (TextView) findViewById(R.id.textView3);
list_toggle = (Switch) findViewById(R.id.mySwitch);
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString("USER_NAME");
user_id = extras.getString("USER_ID");
status = extras.getString("STATUS");
}
if (status.contentEquals("Available")){
ischecked = true;
}
else{
ischecked = false;
}
textView4.setText(Html.fromHtml(status));
list_toggle.setChecked(ischecked);
String[] parts = username.split(" ");
String name = parts[0];
String surname = parts[1];
textView3.setText(Html.fromHtml("Hi, " + name + " "));
Name = name;
list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
textView4.setText(Html.fromHtml("Available"));
} else {
textView4.setText(Html.fromHtml("Unavailable"));
}
}
});
//Tabs
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Orders"));
tabLayout.addTab(tabLayout.newTab().setText("Past Orders"));
tabLayout.addTab(tabLayout.newTab().setText("More"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
checkLogin()は、ユーザーがアプリケーションにログインしているかどうかを確認する必要があります。そうでない場合は、ログインアクティビティ(MainActivity)にリダイレクトされます。
これはAndroidManifestです:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mvaguimaraes.bt">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainScreen"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<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"
android:theme="@style/AppTheme.NoActionBar">
</activity>
<activity android:name=".OrderDetails"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
は、だから私は、アクティビティが最初にオープンすると、 "MainScreen" を設定しようとしました:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
checkLogin(ログイン誰ががない場合)します"MainApplication"アクティビティにリダイレクトします。しかし、これは動作していません。どういうわけか、MainScreenを最初のアクティビティとして設定すると、アプリケーションがクラッシュします。これは、ログインアクティビティからこのメインスクリーンアクティビティにデータ(username、user_id、status)を送信して使用しているからですか?
ありがとうございます!出来た! –
boolをSharedPreferencesに保存できることはご存じですか? –