单击取消按钮时,布尔值不会更改 - 如何停止AsyncTask - Android?

时间:2014-11-27 21:41:36

标签: android android-asynctask boolean

我是初学者,所以请清楚解释一下你的答案。感谢

编辑2 我现在有

public class MainActivity extends Activity {

        //other declarations
        public ReadTask readTask;
    protected void onCreate(Bundle savedInstanceState){
     readTask = new ReadTask();

    private OnClickListener test = new OnClickListener()
        {
            @Override
            public void onClick (View V)
            {
                readTask.execute();
                //new ReadTask().execute();

            }

    };
    private OnClickListener cancel = new OnClickListener()
    {
        @Override
        public void onClick (View V)
        {   
            readTask.cancel(true);
            results1.setText("");
        }

检查编辑1是否存在上述代码(编辑2)抛出的错误; 感谢

  

我在应用程序中有一个取消按钮。点击这个,就是这个   发生;

    public void onClick (View V)
        {
                    InputMethodManager inputManager = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE); 
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                       InputMethodManager.HIDE_NOT_ALWAYS);

            new ReadTask().onCancelled();
            new ReadTask().cancel(true);
            results1.setText("Cancelled");
        }

ReadTask像这样扩展了AsyncTask;

public class ReadTask extends AsyncTask<Void, String, Void>
    {
    BufferedReader reader = null;
    public volatile boolean isCancelled=false;
    //other declarations
    protected void onCancelled() {
        super.onCancelled();
        isCancelled = true;
        new ReadTask().cancel(true);
    }

 @Override
    protected Void doInBackground(Void... params) 
    {
            // isCancelled=false;


        try {
            for(int k=x1[3];k<=x2[3];k++)
            {
                //bunch of code
            Log.w("5.newString", newString);
            String isC1 = String.valueOf(isCancelled);
            Log.w("5.Is cancelled?", isC1); // at this point, VALUE IS ALWAYS FALSE !

            if (isCancelled() || isCancelled == true) {Log.d("Entered","WHY");break;}

                //bunch of code

           } //bunch of catches

这里尝试了两种方法,一种是布尔变量isCancelled,另一种是ReadTask()。cancel(true); - 两个都不起作用。为什么呢?

我是新手,所以请清楚解释一下你的答案。感谢

**************编辑1 - Logcat输出*******

11-27 17:18:56.626: W/dalvikvm(28775): threadid=1: thread exiting with uncaught exception (group=0x41bcee48)
11-27 17:18:56.636: E/AndroidRuntime(28775): FATAL EXCEPTION: main
11-27 17:18:56.636: E/AndroidRuntime(28775): Process: com.example.pingtest, PID: 28775
11-27 17:18:56.636: E/AndroidRuntime(28775): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pingtest/com.example.pingtest.MainActivity}: java.lang.NullPointerException
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.os.Looper.loop(Looper.java:136)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.ActivityThread.main(ActivityThread.java:5103)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at java.lang.reflect.Method.invokeNative(Native Method)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at java.lang.reflect.Method.invoke(Method.java:515)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at dalvik.system.NativeStart.main(Native Method)
11-27 17:18:56.636: E/AndroidRuntime(28775): Caused by: java.lang.NullPointerException
11-27 17:18:56.636: E/AndroidRuntime(28775):    at com.example.pingtest.MainActivity$ReadTask.<init>(MainActivity.java:120)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at com.example.pingtest.MainActivity.onCreate(MainActivity.java:39)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.Activity.performCreate(Activity.java:5275)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-27 17:18:56.636: E/AndroidRuntime(28775):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
11-27 17:18:56.636: E/AndroidRuntime(28775):    ... 11 more
11-27 17:19:05.665: I/Process(28775): Sending signal. PID: 28775 SIG: 9

3 个答案:

答案 0 :(得分:1)

您好我在您的代码中做了一些更改,请说明。

 public class Asyn extends Activity {

    public ReadTask readTask;
    // keep global to prevent creating new async task on every time button click
    boolean isCancelled = true;
    TextView results1;
    Button start, end;

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

        setContentView(R.layout.qww);
        start = (Button) findViewById(R.id.button1);
        end = (Button) findViewById(R.id.button2);
        start.setOnClickListener(test);
        end.setOnClickListener(cancel);
        results1 = (TextView) findViewById(R.id.textView1);
    }

    private OnClickListener test = new OnClickListener() {
        @Override
        public void onClick(View V) {
            if (isCancelled) { // checked to prevent creating new async task on
                                // every time button click
                Toast.makeText(Asyn.this, "new task started", Toast.LENGTH_LONG)
                        .show();
                readTask = new ReadTask();
                readTask.execute();
                isCancelled = false;
            } else {
                Toast.makeText(Asyn.this, "Task already runing",
                        Toast.LENGTH_LONG).show();
            }

        }

    };
    private OnClickListener cancel = new OnClickListener() {
        @Override
        public void onClick(View V) {
            if (null != readTask) {
                Toast.makeText(Asyn.this, "Task stop", Toast.LENGTH_LONG)
                        .show();
                readTask.cancel(true);
                isCancelled = true;
            }
            results1.setText("");
        }
    };

        private class ReadTask extends AsyncTask<Void, String, Void> {


    protected void onProgressUpdate(String... values) {
         super.onProgressUpdate(values);
        results1.setText(values[0].toString());


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

        try {
            for (int k = 0; k <= 10; k++) {
                // bunch of code
                Log.w("5.newString", k + "");
                String isC1 = String.valueOf(isCancelled);
                Log.w("5.Is cancelled?", isC1); // at this point, VALUE IS


                    //below line for instant update as soon as the value is changed
                 publishProgress("  "+k + "");

                // use thread to see the update otherwise remove it
                    Thread.sleep(2000); 
                if (isCancelled() || isCancelled == true) {
                    Log.d("Entered", "WHY");
                    break;
                }

                // bunch of code

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        // assign true to isCancelled so that user can start task again
        isCancelled = true;
    }
}
}

答案 1 :(得分:0)

每次从ReadTask创建新对象时,它都无法正常工作。如果你想取消现有的工作。你应该这样做:

  public class MainActivity extends Activity { 
   ReadTask readTask; 

   @Override
   public void onCreate (Bundle b) {
       ...
       readTask = new ReadTask();

       btnStart.setOnClickListener(new OnClickListener() {
          @Override 
          void onClick(View v) {
            readTask.execute();
          }
       }

       btnCancel.setOnClickListener(new OnClickListener() {
          @Override 
          void onClick(View v) {
            readTask.cancel();
          }
       }
   }

 }

答案 2 :(得分:0)

new ReadTask().onCancelled();
new ReadTask().cancel(true);

这部分代码错误,因为它们都引用了ReadTask类的不同实例。 你可以声明一个ReadTask类的全局变量

public ReadTask rt;

并在onCreate()方法上初始化。

rt = new ReadTask();

然后您就可以在活动的每个部分使用它了 使用rt.execute()启动它并使用rt.cancel(true)

停止它