Android-세션 관리
세션은 사용자 데이터를 응용 프로그램 외부에 저장하려는 경우 도움이되므로 다음에 사용자가 응용 프로그램을 사용할 때 쉽게 세부 정보를 가져와 그에 따라 수행 할 수 있습니다.
이것은 여러 가지 방법으로 수행 될 수 있습니다. 하지만이 작업을 수행하는 가장 쉽고 좋은 방법은Shared Preferences.
공유 기본 설정
공유 기본 설정을 사용하면 키, 값 쌍의 형태로 데이터를 저장하고 검색 할 수 있습니다. 공유 환경 설정을 사용하려면 환경 설정 값이 포함 된 파일을 가리키는 SharedPreference 인스턴스를 반환하는 getSharedPreferences () 메서드를 호출해야합니다.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor 클래스를 사용하여 sharedpreferences에 무언가를 저장할 수 있습니다. SharedPreference 인스턴스의 edit 메서드를 호출하고 편집기 개체에서 수신합니다. 구문은-
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
putString 메소드와는 별도로, 공유 된 환경 설정 내에서 데이터를 조작 할 수있는 편집기 클래스에서 사용할 수있는 메소드가 있습니다. 그들은 다음과 같이 나열됩니다-
Sr. 아니요 | 모드 및 설명 |
---|---|
1 |
apply() 추상적 인 방법입니다. 편집기에서 호출중인 sharedPreference 객체로 변경 사항을 다시 커밋합니다. |
2 |
clear() 편집기에서 모든 값을 제거합니다. |
삼 |
remove(String key) 키가 매개 변수로 전달 된 값을 제거합니다. |
4 |
putLong(String key, long value) 기본 설정 편집기에 긴 값을 저장합니다. |
5 |
putInt(String key, int value) 기본 설정 편집기에 정수 값을 저장합니다. |
6 |
putFloat(String key, float value) 기본 설정 편집기에 부동 값을 저장합니다. |
공유 기본 설정을 통한 세션 관리
공유 기본 설정에서 세션 관리를 수행하려면 공유 기본 설정에 저장된 값 또는 데이터를 onResume방법. 데이터가없는 경우 새로 설치되는 애플리케이션을 처음부터 시작합니다. 그러나 데이터가 있으면 사용자가 데이터를 떠난 곳에서 시작합니다. 아래 예에서 설명합니다.
예
아래 예제는 세션 관리의 사용을 보여줍니다. 처음으로 로그인 할 수있는 기본 응용 프로그램을 만듭니다. 그리고 로그 아웃하지 않고 애플리케이션을 종료하면 애플리케이션을 다시 시작하면 같은 위치로 돌아갑니다. 그러나 응용 프로그램에서 로그 아웃하면 기본 로그인 화면으로 돌아갑니다.
이 예제를 실험하려면 실제 장치 또는 에뮬레이터에서 실행해야합니다.
단계 | 기술 |
---|---|
1 | Android 스튜디오 IDE를 사용하여 com.example.sairamkrishna.myapplication 패키지 아래에 Android 애플리케이션을 만듭니다. |
2 | src / MainActivity.java 파일을 수정하여 진행 코드를 추가하여 세션 코드를 추가합니다. |
삼 | 새 활동을 만들고 이름은 second.java로 지정합니다.이 파일을 편집하여 진행 코드를 추가하여 세션 코드를 추가합니다. |
4 | res / layout / activity_main.xml 파일을 수정하여 각 XML 코드를 추가하십시오. |
5 | res / layout / second_main.xml 파일을 수정하여 각 XML 코드를 추가합니다. |
7 | 애플리케이션을 실행하고 실행중인 Android 기기를 선택하고 여기에 애플리케이션을 설치하고 결과를 확인합니다. |
내용은 다음과 같습니다. MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button b1;
Intent in;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
in = new Intent(MainActivity.this,second_main.class);
startActivity(in);
}
});
}
}
내용은 다음과 같습니다. second_main.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class second_main extends Activity {
Button bu=null;
Button bu2=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
bu=(Button)findViewById(R.id.button2);
bu2=(Button)findViewById(R.id.button3);
}
public void logout(View view){
SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
}
public void close(View view){
finish();
}
}
내용은 다음과 같습니다. activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
</RelativeLayout>
내용은 다음과 같습니다. second_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:onClick="logout"
android:id="@+id/button2"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="191dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:onClick="close"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp" />
</RelativeLayout>
내용은 다음과 같습니다. Strings.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
내용은 다음과 같습니다. AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
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=".second"></activity>
</application>
</manifest>
애플리케이션을 실행 해 보겠습니다. 환경 설정을하는 동안 AVD를 만들었다 고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고


사용자 이름과 비밀번호를 입력하세요 (type anything you like, but remember what you type), 로그인 버튼을 클릭합니다. 아래 이미지에 나와 있습니다.

로그인 버튼을 클릭하면이 시작 화면으로 이동합니다. 이제 로그인 정보가 공유 기본 설정에 저장됩니다.

이제 클릭 Exit without logout 버튼을 누르면 홈 화면으로 돌아 오며 기본 설정 파일에 출력되는 내용은 아래와 같습니다.

myPref.xml 파일을 노트 파일로 열면 다음과 같습니다.

로그 아웃 버튼을 클릭하면 기본 설정 값이 지워집니다. 입력으로 다른 값을 입력 한 경우 해당 값을 XML의 기본 설정으로 입력합니다.