android - 使用共享首选项一次性登录?

标签 android authentication sharedpreferences

这可能是重复的问题,但我仍然找不到解决方案,因为我是 Android 新手,我使用共享首选项进行登录 Activity ,我的要求它不应该显示登录页面,除非我们注销,到目前为止我该怎么做?尝试过的是

主要 Activity :

package first.service.precision.servicefirst;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
  //  public EditText password, userName;
    Button login, resister;
    ProgressBar progressbar;

public static String s1,s2;
    TextView tv;
    public static final String pref="login";
    String TAG = "Fails";
    String url = "http://172.16.7.203/sfAppServices/SF_UserLogin.svc";
    private ModelLogin Result;
    SharedPreferences sharedPreferences;
   private SharedPreferences sharedpreferences;
  //  public static final String MyPREFERENCES = "MyPrefs" ;
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences shared=getSharedPreferences(pref,0);
        Boolean logins=shared.getBoolean("do",false);

        if(logins){
            Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
            startActivity(intent);
        }


        setContentView(R.layout.activity_main);
   final EditText     userName = (EditText) findViewById(R.id.txtEmployeeCode);
        final EditText      password = (EditText) findViewById(R.id.password);


     login = (Button) findViewById(R.id.btnsignin);
        userName.setBackgroundResource(R.drawable.colorfoucs);
        ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected() == true) {
            Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        }
        else
        {
            showAlertDialog(MainActivity.this, "No Network", "Please Check Your Network Connectivity", true);
        }
        //}

        final ConnectionDetector cd = new ConnectionDetector(getApplicationContext());

        login.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v) {
              //  sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                progressbar = (ProgressBar) findViewById(R.id.progressBar);
                progressbar.setVisibility(View.VISIBLE);
                s1 = userName.getText().toString();
                s2 = password.getText().toString();
         SharedPreferences     sharedPreferences=getSharedPreferences(pref, 0);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("do",true);
                 editor.putString("yog",s1);
                editor.putString("pass",s2);
                editor.commit();

                if (s1.equals("")) {
                    userName.setError("Enter Employee Code");
                }
                if (s2.equals("")) {
                    password.setError("Enter Password");

                }
                Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                Toast.makeText(MainActivity.this, "Welcome_"  +""+  s1, Toast.LENGTH_SHORT).show();
                startActivity(intent);
/*                RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
                RetrofitRest retro = adapter.create(RetrofitRest.class);
                retro.getResult(s1, s2, new Callback<ModelLogin>() {
                    @Override
                    public void success(ModelLogin modelLogin, Response response) {
                        if (modelLogin.getResult().equals(1)||modelLogin.getModuleID().equals(1)) {


                            progressbar.setVisibility(View.INVISIBLE);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        progressbar.setVisibility(View.INVISIBLE);

                        Toast.makeText(MainActivity.this, "Login Fails", LENGTH_SHORT).show();
                    }
                });*/


            }

        });

      //  if(sharedpreferences.contains(s1)) {
          //


    }















    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon


        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

}















    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon


        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

}

它只是行为不当,就像第一次从第二次重定向到新的登录屏幕进入主屏幕一样。不知道我在哪里做错了,如果有人找到我的答案的解决方案,那将非常有帮助

最佳答案

尝试在没有布局的情况下创建启动器 Activity ,然后将您的首选项检查放在这里并开始下一个 Activity 。

  • 启动器 Activity (如果存在凭据)-> MainActivity

  • 启动器 Activity (如果凭据不存在)-> LoginActivity

StartActivity.java

public class StartActivity extends AppCompatActivity {

private static final String PREF_LOGIN = "LOGIN_PREF";
private static final String KEY_CREDENTIALS = "LOGIN_CREDENTIALS";


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences preferences = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE);

    Intent intent = null;
    if(preferences.contains(KEY_CREDENTIALS)){              //if user is currently logged in;
        intent = new Intent(this, MainActivity.class);
    }else {                                                 //if user is not yet logged in;
        intent = new Intent(this, LoginActivity.class);
    }
    startActivity(intent);
}

}

LoginActivity.java

public class LoginActivity extends AppCompatActivity {

public static final String PREF_LOGIN = "LOGIN_PREF";
public static final String KEY_CREDENTIALS = "LOGIN_CREDENTIALS";

private Button loginButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //...

    loginButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            //call login api...


            //on your sucess callback; we save the credentials...
            /*
            SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
            editor.putString(KEY_CREDENTIALS, "DUMMY CREDENTIALS");
            editor.commit();
            */

            //on your failure callback; we clear the credentials...

            /*
            SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
            editor.clear();
            editor.commit();
            */
        }


    });
}

}

关于android - 使用共享首选项一次性登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454502/

相关文章:

authentication - 如何在 Rails 3.2 中使用回形针毫无错误地检索 facebook、twitter 和 google 个人资料图像

android 首选项在同一个 PreferenceActivity 中更改显示的首选项

java - 使用GCM可以吗?

java - Android ksoap嵌套soap对象给出无法读取请求错误

Laravel 隔离管理员登录

postgresql - psql: 数据库 "dbname"("User does not have CONNECT privilege.")/"unrecognized role option ' 连接权限被拒绝'"

java - 为共享首选项自动生成 getter setter

Android SharedPreferences 没有改变

android - 如何在 ktlint 中禁用文件名?

java - 我应该在 OnBindViewHolder() 方法中设置 ReyclerView 项目的 OnClickListener 吗?