【问题标题】:app log out automatically after some time应用程序在一段时间后自动注销
【发布时间】:2018-09-03 20:07:00
【问题描述】:

当用户在我的 android 应用程序中登录时,我将服务器返回的令牌保存在共享偏好中,并且仅在注销时将其清除。但是当我在一段时间后关闭应用程序时,它需要再次登录。这是我的共享偏好类

        package com.example.narmail.truck30mint.Api.models.UserModels;

        import android.content.Context;
        import android.content.SharedPreferences;

        import com.google.gson.annotations.Expose;
        import com.google.gson.annotations.SerializedName;

        public class User {

          public static   SharedPreferences sharedPreferences;
            Context context;
            @SerializedName("token")
            @Expose
            private static String token;

            /**
             * No args constructor for use in serialization
             *
             */
            public User(Context context) {
                super();
                this.context = context;
                sharedPreferences  = context.getSharedPreferences("user_token",Context.MODE_PRIVATE);
            }

            /**
             *
             * @param //token
             */
          /*  public User(String token) {
                super();
                this.token = token;
            }*/

            public static String getToken() {

                if(sharedPreferences.getString(token,null) != null){
                token = sharedPreferences.getString(token,null);
                };
                return token;
            }

            public void setToken(String token) {
                this.token = token;
                sharedPreferences.edit().putString("token",token).apply();
            }
            public static void removeToken(){
                if(sharedPreferences.contains("token")){
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.remove("token").commit();
                    token = null;   //Missing this
                    System.out.println("shared preference deleting ");
                }else{
                    System.out.println("not contain key token ");
                }
            }

        }

这是检查令牌是否存储在共享首选项中的主要活动

package com.example.narmail.truck30mint.Api.Activities;

        import android.app.Activity;
        import android.content.Context;
        import android.content.Intent;
        import android.location.Location;
        import android.location.LocationListener;
        import android.location.LocationManager;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;

        import com.example.narmail.truck30mint.Api.models.UserModels.User;
        import com.example.narmail.truck30mint.R;

        public class MainActivity extends AppCompatActivity {
            public String token = null;
            private Context context;
            public static Activity activity = null;

        //save the context received via constructor in a local variable

           /* public MainActivity(Context context) {
                this.context = context;
            }*/
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                User user = new User(getApplicationContext());
                activity = this;
                token = user.getToken();
                System.out.println("in main activity token is "+token);
                if (token != null && !token.equalsIgnoreCase("")) {
                    Intent a = new Intent(MainActivity.this, DashboardActivity.class);
                    startActivity(a);
                }else if(token == null){
                    setContentView(R.layout.activity_main);
                    Button btnNewUser = findViewById(R.id.newUser);
                    Button btnExistingUser = findViewById(R.id.existingUser);

                    btnExistingUser.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent a = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(a);
                          //  MainActivity.this.finish();
                        }
                    });

                    btnNewUser.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(MainActivity.this, RegisterActivity.class);
                            startActivity(i);
                           // MainActivity.this.finish();
                        }
                    });
                }



                    // Acquire a reference to the system Location Manager
                    LocationManager locationManager =
                            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    // Define a listener that responds to location updates
                    LocationListener locationListener = new LocationListener() {
                        public void onLocationChanged(Location location) {
                            // Called when a new location is found by the network location provider.
                           String lat = Double.toString(location.getLatitude());
                          String  lon = Double.toString(location.getLongitude());
                        }

                        public void onStatusChanged(String provider, int status, Bundle extras) {}
                        public void onProviderEnabled(String provider) {}
                        public void onProviderDisabled(String provider) {}
                    };
                 /*   if(checkPermission(Location,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)){
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                    }*/
                    // Register the listener with the Location Manager to receive location updates
            }
        }

如果登录成功,我通过此方法存储共享偏好

 User user= new User(loginContext);
                    user.setToken(token);

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    在 User 类的 setToken(String token) 方法中尝试使用 .commit() 方法而不是 .apply() 。它将返回布尔值,确认登录。不确定,但应该可以。

    【讨论】:

      【解决方案2】:

      我自己解决了 这里是修改后的 user.java 文件

          package com.example.narmail.truck30mint.Api.models.UserModels;
      
          import android.content.Context;
          import android.content.SharedPreferences;
      
          import com.google.gson.annotations.Expose;
          import com.google.gson.annotations.SerializedName;
      
          public class User {
      
            public static   SharedPreferences sharedPreferences;
              Context context;
              @SerializedName("token")
              @Expose
              private static String token;
      
              /**
               * No args constructor for use in serialization
               *
               */
              public User(Context context) {
                  super();
                  this.context = context;
                  sharedPreferences  = context.getSharedPreferences("user_token",Context.MODE_PRIVATE);
              }
      
              /**
               *
               * @param //token
               */
             /* public User(String token) {
                  super();
                  this.token = token;
              }*/
      
              public static String getToken() {
      
                  if(sharedPreferences.getString("token",null) != null){
                  token = sharedPreferences.getString("token",null);
                  };
                  return token;
              }
      
              public void setToken(String token) {
                  this.token = token;
                  sharedPreferences.edit().putString("token",token).commit();
              }
              public static void removeToken(){
                  if(sharedPreferences.contains("token")){
                      SharedPreferences.Editor editor = sharedPreferences.edit();
                      editor.remove("token").commit();
                      token = null;   //Missing this
                      System.out.println("shared preference deleting ");
                  }else{
                      System.out.println("not contain key token ");
                  }
              }
      
          }
      

      【讨论】:

      • 请简要说明您为使其工作所做的工作。
      猜你喜欢
      • 2013-08-19
      • 1970-01-01
      • 2015-02-18
      • 2012-08-26
      • 2013-09-23
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      相关资源
      最近更新 更多