如何实现LogIn和;在Android中注册只能运行一次?

时间:2013-10-03 11:57:41

标签: android android-activity sharedpreferences

我正在办理登记表格。它是启动画面后应用程序的第二页,它显示了一个登录表单和两个按钮:登录和注册。当我们点击注册时,它有一个注册表单,其中包含两个按钮:注册和退出。

当用户第一次进入时,他需要登录或注册,当按下“注册”时,注册过程将开始。用户必须提供用户名,密码,电子邮件地址和手机号码。一旦他填写了所有这些信息,他就可以使用用户名和密码登录。

所有这一部分都运行正常,但我的要求是在注册后,一旦我的应用程序使用splash和MainActivity重新启动,就会停用注册(活动)和登录(活动)。那么我该怎么做才能做到这一点呢?任何人都能帮助我吗?

如何停用以splashActivity开头的LoginActivity和SignUpActivity,一旦注册以splash启动,主Activity再次以启动开始。

SplashActivity

public class SplashScreen extends Activity {
    private long splashDelay = 5000; //5 seconds

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        TimerTask task = new TimerTask()
        {

            @Override
            public void run() {
                finish();
                Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
                startActivity(mainIntent);
            }

        };

        Timer timer = new Timer();
        timer.schedule(task, splashDelay);
    }
}

登录

public class LoginActivity extends Activity {

    Intent i;
    Button signin, signup;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signin = (Button) findViewById(R.id.signin);
        signup = (Button) findViewById(R.id.signup);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        check = (CheckBox) findViewById(R.id.check);
        String Str_user = app_preferences.getString("username", "0");
        String Str_pass = app_preferences.getString("password", "0");
        String Str_check = app_preferences.getString("checked", "no");
        if (Str_check.equals("yes")) {
            editTextId.setText(Str_user);
            editTextP.setText(Str_pass);
            check.setChecked(true);
        }

    }

    public void Move_to_next() 
    {
        final Handler handle = new Handler();
        Runnable delay = new Runnable() {
            public void run() {
                startActivity(new Intent(LoginActivity.this, SplashActivity.class));
                finish();
            }
        };
        handle.postDelayed(delay,2000);

    }

    public void Move_next() 
    {
        startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
        finish();
    }

    @SuppressLint("NewApi")
    private class LoginTask extends AsyncTask <Void, Void, String> 
    {
        @SuppressLint("NewApi")
        @Override
        protected void onPreExecute() 
        {

            super.onPreExecute();
            // Show progress dialog here
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://xxx/login1.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
                return buffer.toString();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();

            }
            return "";
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                Move_to_next();
            } else {
                Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }

7 个答案:

答案 0 :(得分:3)

我会在这里试试这段代码:

final Class<?> target;
boolean isUserLoggedIn = app_preferences.getBoolean("checked", false);
if(isUserLoggedIn) {
    target = MainActivity.class;
} else {
    target = Login.class;
}

TimerTask task = new TimerTask() {

    @Override
    public void run() {
        finish();
        Intent mainIntent = new Intent().setClass(SplashScreen.this, target);
        startActivity(mainIntent);
    }

};

Timer timer = new Timer();
timer.schedule(task, splashDelay);

顺便说一下Ralph Pina已经指出,avoid using splashscreens一般来说,它们在Android上并不常见。不过,我还建议不要在您的应用中存储任何信用卡。特别是在存储的偏好中。它们是普通的xml文件,可以在root设备上读取。更好地在您的应用中的某处存储像会话cookie一样的令牌。

答案 1 :(得分:2)

setContentView(R.layout.splash_screen);
       pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
       Log.v("","onCreate is calling");
       if(pref.getBoolean("activity_executed", false))
       {
            Log.v("","Before if called");
           setContentView(R.layout.splash_screen);
            Log.v("","after if called");
            new Handler().postDelayed(csRunnable1, 3000);

       } 
       else 
       {
          new Handler().postDelayed(csRunnable2, 3000);  
           Editor ed = pref.edit();
           ed.putBoolean("activity_executed", true);
           ed.commit();

       }
   }

   Runnable csRunnable1=new Runnable() 
   {       
       @Override
       public void run() 
       {
            Intent intent = new Intent(SplashScreen.this, SplashActivity.class);
               startActivity(intent);
               finish();

       }
   };

   Runnable csRunnable2=new Runnable() 
    {      
       @Override
       public void run() 
       {
            Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
               startActivity(intent);
               finish();

       }
   };

尝试使用此代码来帮助您

答案 2 :(得分:1)

根据Android设计指南http://developer.android.com/design/patterns/help.html,建议不要使用启动页面。为什么要让用户等待5秒才能访问您的应用程序?

我已根据我的反馈/答案评论了您的代码。

只需使用SharedPreferences。这是最简单的方法:

public class SplashScreen extends Activity {
    private long splashDelay = 5000; //5 seconds

    private Activity splashScreen;
    private Intent intent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        splashScreen = this;

        // get your shared preferences stored in your app. If the username has been
        // set then this user has already logged in    
        SharedPreferences prefs = getSharedPreferences("name_for_file", 0);
        // return the username of null if none exists
        String username = prefs.getString("username", null);

        // if user has already logged in, just go to MainActivity
        if (username == null) {
             intent = new Intent(this, LoginActivity.class);
        } else {
             intent = new Intent(this, MainActivity.class);
        }

        TimerTask task = new TimerTask()
        {

            @Override
            public void run() {
                //finish(); <- you don't need to call finish, the OS takes care of that

                splashScreen.startActivity(intent);
            }

        };

        Timer timer = new Timer();
        timer.schedule(task, splashDelay);
    }
}


public class LoginActivity extends Activity {

    Intent i;
    Button signin, signup;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;
    Activity loginActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        loginActivity = this;
        signin = (Button) findViewById(R.id.signin);
        signup = (Button) findViewById(R.id.signup);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        // app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        app_preferences = getSharedPreferences("name_of_file", 0);
        check = (CheckBox) findViewById(R.id.check);
        // if they got to this activity they are not logged in, so why are you
        // checking here?
        // the common pattern is to use null
        // String Str_user = app_preferences.getString("username", null);
        // String Str_pass = app_preferences.getString("password", null);
        // checked only has two states, use a boolean
        // boolean Str_check = app_preferences.getBoolean("checked", false);
        // if (Str_check)) {
        //    editTextId.setText(Str_user);
        //    editTextP.setText(Str_pass);
        //    check.setChecked(true);
        // }

        signin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                 LoginTask login = new LoginTask();
                 login.execute();
            }
         });

         signup.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                 Intent intent = new Intent(this, SignUpActivity.class)
                 startActivity(intent);
            }
         });


    }

    // why are you sending them back to the splash?
    public void Move_to_next() 
    {
        final Handler handle = new Handler();
        Runnable delay = new Runnable() {
            public void run() {
                startActivity(new Intent(LoginActivity.this, SplashActivity.class));
                finish();
            }
        };
        //why are you making people wait?
        handle.postDelayed(delay,2000);

    }

    // This is never being called
    public void Move_next() 
    {
        startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
        //finish(); <- the OS will do this
    }

    @SuppressLint("NewApi")
    private class LoginTask extends AsyncTask <Void, Void, String> 
    {
        @SuppressLint("NewApi")
        @Override
        protected void onPreExecute() 
        {

            super.onPreExecute();
            // Show progress dialog here
        }

        // best practice for android is to use HttpUrlConnection: 
        // http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        // there is also AndroidHttpClient, which is the class google used in their
        // Google IO 2013 app. It is pretty clean. https://code.google.com/p/basic-http-client/
        /*
        AndroidHttpClient httpClient = new AndroidHttpClient("http://www.google.com");
        ParameterMap params = httpClient.newParams().add("q", "GOOG");
        httpClient.setMaxRetries(3);
        httpClient.get("/finance", params, new AsyncCallback() {
            public void onComplete(HttpResponse httpResponse) {
                System.out.println(httpResponse.getBodyAsString());
            }
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
        */
        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://xxx/login1.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
                return buffer.toString();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();

            }
            return "";
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoginActivity.this, "login successful", Toast.LENGTH_SHORT).show();
                // don't send them back to the splash, they are logged in
                // save username and pass, and move forward
                SharedPreferences settings = loginActivity.getSharedPreferences("name_of_file", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("username", put whatever you get from server).commit();
                editor.putString("password", put whatever you get from server).commit();
                Intent intent = new Intent(loginActivity, WelcomeActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }

答案 3 :(得分:0)

登录/注册完成后将其保存在SharedPreferences中。将布尔标志设为true并保存在SharedPreferences中。 在启动画面上检查此标志。如果真的去主动,那么去注册活动。

答案 4 :(得分:0)

在android中你需要在持久性存储中存储任何变量的值(布尔值或任何你觉得舒服的),如数据库或共享首选项,并在启动活动之前检查此值,如果value为true则表示用户已经注册,如果值为false表示您需要再次显示login或siginup活动。

编辑在启动之前检查该变量的值

<强> SplashActivity

public class SplashScreen extends Activity {
private long splashDelay = 5000; //5 seconds

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_screen);

    TimerTask task = new TimerTask()
    {

        @Override
        public void run() {
            finish();
// someBoolean  which is stored sharedprefs in your second or login activity
if(someBoolean = true)
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
            startActivity(mainIntent)

答案 5 :(得分:0)

登录/注册成功后,您可以在SharedPreferences中设置布尔值,并且可以检查启动画面并确定要显示的屏幕。

答案 6 :(得分:0)

您可以对show SignIn和SignUp Once使用共享首选项。

这是我的启动画面代码。

public class Splash extends Activity {

SessionManage sm;
Context _context;
Thread timer= new Thread(){
    public void run(){
        try{
            sleep(2000);
        }catch(InterruptedException axe){
            axe.printStackTrace();
        }finally{
            sm= new SessionManage(_context);
            startActivity(sm.checkLogin());

        }

    }
        };

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

    setContentView(R.layout.splash);
    this._context= getApplicationContext();

timer.start();

}

这是我的会话管理器类

public class SessionManage {
SharedPreferences share;
public static final String filename= "data";
SharedPreferences.Editor editor;
Context _context;
String sname,semail;
ArrayList<String> BookArray;
Set<String> set;
@SuppressLint("CommitPrefEdits")
public SessionManage(Context context){
    this._context= context;
    share = _context.getSharedPreferences(filename, 0);
    editor = share.edit();

}

public void login(String lname, String lemail){
    this.sname= lname;
    this.semail= lemail;

    editor.putString("name", lname);
    editor.putString("email", lemail);

    editor.commit();
}

public Intent checkLogin(){
    Intent vs;

    semail= share.getString("email", "Guest");
     if (semail.equalsIgnoreCase("Guest")){
         vs= new Intent(_context, Login.class );
     }
     else{
         vs= new Intent(_context, Populer.class );
     }
     return vs;
}

这是在登录活动中点击登录按钮的代码。

    sm= new SessionManage(getApplicationContext());
        vs= new Intent(getApplicationContext(), Populer.class);
        sm.login(sname, semail);
   }