• Android Video Tutorials

Android - 会话管理



当您想将用户数据存储在应用程序外部时,会话会帮助您,以便下次用户使用您的应用程序时,您可以轻松地获取他的详细信息并相应地执行操作。

这可以通过多种方式完成。但是,最简单也是最不错的方法是通过**共享首选项**。

共享首选项

共享首选项允许您以键值对的形式保存和检索数据。为了使用共享首选项,您必须调用一个名为 getSharedPreferences() 的方法,该方法返回一个指向包含首选项值的文件的 SharedPreference 实例。

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);	

您可以使用 SharedPreferences.Editor 类将某些内容保存到共享首选项中。您将调用 SharedPreference 实例的 edit 方法,并将其接收在编辑器对象中。其语法如下:

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

除了 putString 方法外,编辑器类中还提供了其他方法,允许操作共享首选项中的数据。它们列出如下:

序号 模式及描述
1

apply()

这是一个抽象方法。它将把您的更改从编辑器提交回您调用的 SharedPreference 对象。

2

clear()

它将删除编辑器中的所有值。

3

remove(String key)

它将删除键作为参数传递的值。

4

putLong(String key, long value)

它将在首选项编辑器中保存一个长整型值。

5

putInt(String key, int value)

它将在首选项编辑器中保存一个整型值。

6

putFloat(String key, float value)

它将在首选项编辑器中保存一个浮点型值。

通过共享首选项进行会话管理

为了从共享首选项执行会话管理,我们需要在**onResume**方法中检查存储在共享首选项中的值或数据。如果我们没有数据,我们将从头开始应用程序,因为它新安装。但如果我们获得了数据,我们将从用户离开的地方开始。这在下面的示例中进行了演示:

示例

以下示例演示了会话管理的使用。它创建一个基本的应用程序,允许您首次登录。然后,如果您退出应用程序而没有注销,则如果再次启动应用程序,您将被带回同一位置。但是,如果您从应用程序注销,则您将被带回主登录屏幕。

要体验此示例,您需要在实际设备或模拟器上运行它。

步骤 描述
1 您将使用 Android Studio IDE 在包 com.example.sairamkrishna.myapplication 下创建一个 Android 应用程序。
2 修改 src/MainActivity.java 文件以添加进度代码以添加会话代码。
3 创建新的 Activity 并将其命名为 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 Studio 运行应用程序,请打开您的项目之一的活动文件,然后单击工具栏中的运行Eclipse Run Icon图标。Android Studio 将应用程序安装到您的 AVD 上并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口:

Anroid Session Management Tutorial

输入您的用户名和密码**(输入任何您喜欢的内容,但请记住您输入的内容)**,然后单击登录按钮。如下面的图片所示:

Anroid Session Management Tutorial

单击登录按钮后,您将进入此欢迎屏幕。现在您的登录信息存储在共享首选项中。

Anroid Session Management Tutorial

现在单击**退出而不注销**按钮,您将返回主屏幕,并且首选项文件输出将如下面的图片所示

Anroid Session Management Tutorial

如果您将 myPref.xml 文件作为记事本文件打开,它将如下所示

Anroid Session Management Tutorial

如果您单击注销按钮,它将擦除首选项值。如果您输入了不同的值作为输入,它将把这些值作为 XML 中的首选项输入。

广告