在Android中停止AsyncTask doInBackground方法

时间:2016-03-07 10:39:34

标签: java android

我遇到AsyncTask doInBackground方法的问题,我不知道如何阻止此方法运行。

我正在开发一个具有登录屏幕的应用程序,该屏幕可以检索有关已登录用户的信息。问题是当我输入错误的密码或用户名然后当我重新输入正确的数据时,我的应用程序崩溃了,我得到了

  

“java.lang.IllegalStateException:无法执行任务:任务有   已被执行“

如何阻止此线程运行?这是代码:

LoginActivity.java

public class LoginActivity extends Activity implements LoginParser.GetLoginListener{


    public LoginParser parser1;
    public EditText ETUsername;
    public  EditText ETPassword;
    //private LoginParser lb;


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


      parser1 = new LoginParser();

        ETUsername = (EditText)findViewById(R.id.ET1);
        ETPassword = (EditText)findViewById(R.id.ET2);

        final Button button = (Button) findViewById(R.id.loginBut);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String UserName = ETUsername.getText().toString();
                String Password = ETPassword.getText().toString();
                Log.e("LoginAct .. userName: ", UserName);
                Log.e("LoginAct .. Password: ", Password);

                if (UserName.isEmpty() || Password.isEmpty()) {
                    new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
                            .setMessage("Please Enter your Username and Password")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                }

                else{

                    parser1.getLoginInfo(UserName, Password);
                    parser1.setListener(LoginActivity.this);
                }
            } // end of button on click
        } );
}

    @Override
    public void didReceivedUserInfo(String displayName) {

        if(displayName != null) {

                        new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName)
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent in = new Intent (LoginActivity.this, MainActivity.class);
                                        startActivity(in);
                                    }
                                }).show();
                    }

                else {

                    new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
                            .setMessage("Error in login ID or Password, Please try again later")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).show();
                }
  }
}

LoginParser.java

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

    private String requestURL;

    public  String UserName ;
    public  String Password ;



    public interface GetLoginListener
    {
        public void didReceivedUserInfo (String displayName);
    }

    private GetLoginListener listener;


    public GetLoginListener getListener() {
        return listener;
    }

    public void setListener(GetLoginListener listener) {
        this.listener = listener;
    }


    public void getLoginInfo(String userName , String password)
    {
        requestURL = "some link";

        this.UserName = userName ;
        this.Password = password ;

        execute(); // it will call doInBackground in secondary thread
    }




    @Override
    protected String doInBackground(Void... params) {

        try {

            URL url = new URL(requestURL);

            HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();


            String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****";
            Log.e("LoginParser","JSONString: " + jsonString);


            urlConnection1.setDoOutput(true);
            urlConnection1.setRequestMethod("POST");
           urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
             urlConnection1.setRequestProperty("charset","utf-8");


            PrintWriter out = new PrintWriter(urlConnection1.getOutputStream());
            // out.print(this.requestMessage);
            out.print(jsonString);
            out.close();

            int statusCode = urlConnection1.getResponseCode();
            Log.d("statusCode", String.valueOf(statusCode));
            StringBuilder response = new StringBuilder();

            byte[] data = null;

            if (statusCode == HttpURLConnection.HTTP_OK)
            {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream()));

                String line;

                while ((line = r.readLine()) != null) {
                    response.append(line);
                }

                data = response.toString().getBytes();
            }

            else {

                data = null;// failed to fetch data
            }

            String responseString = new String(data);
            Log.e("doInBackground", "responseString" + responseString);

            JSONObject jsonObject2 = new JSONObject(responseString);
            String Status = jsonObject2.getString("Status");
            Log.e("Status", Status);

            if (Status.equals("s")) {


                Log.i("Status:", "Successful");

                String displayName = jsonObject2.getString("DisplayName");


                return displayName;
            }

            else {

                return null;

            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String displayName) {
        super.onPostExecute(displayName);

        Log.e("onPost: ","onPost");
        listener.didReceivedUserInfo(displayName);
    }
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

&#34>无法重新执行任务&#34;可以通过创建AsyncTask的新实例来解决错误。您无法在同一个实例上调用执行两次,但您可以根据需要创建任意数量的实例。

停止执行不会帮助解决该错误。问题不是它当前正在运行,问题是您需要创建一个新实例并运行它。

答案 1 :(得分:0)

您可以在doInBackground方法中使用isCancel的连续检查来取消异步任务。

protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }

希望这会对你有所帮助。