0

我正在填写注册表。它是应用程序在初始屏幕之后的第二个页面,其中显示了一个登录表单和两个按钮:登录和注册。当我们点击注册时,它有一个带有两个按钮的注册表单:注册和退出。

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

所有这部分工作正常,但我的要求是注册后,一旦我的应用程序以启动和 MainActivity 重新启动,注册(活动)和登录(活动)将被停用。那么我必须做些什么才能使这项工作发挥作用?谁能帮我这个?

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

飞溅活动

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();
            }
        }
    }
4

7 回答 7

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已经指出,一般来说,您应该避免使用闪屏,它们在 Android 上并不常见。但是,我也建议不要在您的应用程序中存储任何凭据。特别是在存储的偏好中。它们是纯 xml 文件,可以在有根设备上读取。最好在您的应用程序中的某处存储像会话 cookie 这样的令牌。

于 2013-10-04T10:16:08.460 回答
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();

       }
   };

试试这个可以帮助你的代码

于 2013-10-04T08:52:05.580 回答
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();
            }
        }
    }
于 2013-10-03T13:09:22.430 回答
0

登录/注册完成后,将其保存在SharedPreferences.put 布尔标志为 true 并保存在SharedPreferences. 在初始屏幕上检查此标志。如果它是真的去 mainactivity 否则去注册活动。

于 2013-10-03T12:01:40.527 回答
0

在android中,您需要将任何变量的值(布尔值或任何您觉得舒服的值)存储在持久性存储中,例如数据库或sharedpreference,并在启动活动之前检查此值,如果值为true,则表示用户已经注册并且该值为false 表示您需要再次显示登录或注册活动。

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

飞溅活动

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)
于 2013-10-03T12:02:22.970 回答
0

登录/注册成功后,您可以在 SharedPreferences 中设置一个布尔值,然后您可以检查您的初始屏幕并决定必须显示哪个屏幕。

于 2013-10-03T12:04:12.867 回答
0

您可以使用共享首选项来显示登录和注册一次。

这是我的启动画面代码。

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();

计时器.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);
   }
于 2013-10-03T12:18:24.193 回答