Android 记住以前的登录(后台任务)

Android remembering previous login (backgroundtask)

我正在尝试登录以检查用户是否存在于 mysql 数据库中,但是当 运行 应用程序会记住之前的登录详细信息。我认为问题出在后台任务中,就好像我将其注释掉一样我可以很好地记录登录详细信息。

public class Tab1Activity extends Activity 
{   
    String task,username,password;

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

        final Button buta = (Button) findViewById(R.id.button1);
        final Button butb = (Button) findViewById(R.id.button2);
        final TextView usernameTV = (TextView) findViewById(R.id.editText1);
        final TextView passwordTV = (TextView) findViewById(R.id.editText2);

        buta.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                 SharedPreferences  preferences = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
                 //editor = preferences.edit();

                 username=usernameTV.getText().toString(); 
                 password=passwordTV.getText().toString();
                 task="login";
                 Toast.makeText(getApplicationContext(), username+" "+password, Toast.LENGTH_SHORT).show();

                 // create and call background activity                                

                 BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);                
                 backgroundTaskLogin.execute(task,username,password);

                 //get data back from sharedpreference
                 String driver_exist = preferences.getString("myDatalogin","ERROR getting name");

                 //display datas
                 String[] loginSeparated = driver_exist.split(",");
                 Toast.makeText(getApplicationContext(), loginSeparated[0], Toast.LENGTH_SHORT).show();


               if (loginSeparated[0].equals("true"))
               {

                int finalId = Integer.parseInt(loginSeparated[1]);   
                //Toast.makeText(getApplicationContext(), loginSeparated[1], Toast.LENGTH_SHORT).show();

                SharedPreferences.Editor editor = getSharedPreferences("MYPREFS",  Context.MODE_PRIVATE).edit();
                editor.putInt("TaxiDriverId", finalId);
                editor.apply();

                //once clicked - jump to tab2
                TabActivity tabs = (TabActivity) getParent();
                tabs.getTabHost().setCurrentTab(1);
               }
               else
               {
                   Toast.makeText(getApplicationContext(), "Wrong password", Toast.LENGTH_SHORT).show();
               }
            }
        });
    }

    //////////////////////////////////////////////////////
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tab1, menu);
        return true;
        }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

这是我认为问题所在的背景谈话。

public class BackgroundTask extends AsyncTask<String,Void,String>
    {

        SharedPreferences preferences;
        SharedPreferences.Editor editor;
        SharedPreferences.Editor pig;

        Context context;

        BackgroundTask(Context ctx)
        {
            this.context = ctx;
        }

        @Override
        protected String doInBackground(String... params)
        {
            String urlLogin  = "";
            preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
            editor = preferences.edit();
            editor.putString("flag","0");
            editor.commit();

            String task = params[0];
            String loginusername;
             String loginpassword;


            if (task.equals("login"))
            {          
              urlLogin  = "http://super.com/LoginAndRegister-login.php";
              loginusername = params[1];
              loginpassword = params[2];



                try 
                {
                    URL url = new URL(urlLogin);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);


                    //send the driver number to the database
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
                    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

                    String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
                    +"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
                    bufferedWriter.write(myDatalogin);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();

                    //get response from the database
                    InputStream inputStream = httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String dataResponse = "";
                    String inputLine = "";
                     while((inputLine = bufferedReader.readLine()) != null)
                     {
                        dataResponse += inputLine;
                     }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();

                    editor.putString("flag","login");
                    editor.commit();                                      
                    pig = preferences.edit();
                    pig.putString("myDatalogin",dataResponse);
                    pig.commit();               
                    return  dataResponse;
                } 
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                } 

            }//end if statement

当您完成 Activity 调用 finish() 时,这将确保下次 activity 启动时它将重新开始。还要查看 AndroidManifest.xmlActivity 标记中的 launchMode 属性,以确保正确启动 activity。 https://developer.android.com/guide/topics/manifest/activity-element.html