java - 计数器不会在 AsyncTask 的新实例中重新启动

标签 java android android-asynctask

所以,我只有一个 Android 应用程序,在您按下“开始”按钮后,它会每秒增加一次计数器。这是在 AsyncTask 中完成的,并通过调用 Thread.sleep(1000); 每秒递增一次。当按下停止按钮时,任务被取消,但是当再次按下开始按钮时,按钮上的文本更改为“停止”,但计数器似乎没有启动(TextView 不更新,并且 计数器的 System.out.println 不显示)。

当按下停止按钮时,任务将被取消,并将一个新实例分配给变量:

package com.lukechenshui.timelapse;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    CounterTask task = new CounterTask();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    }

    public void toggleTimer(View view){
    Button button = (Button)findViewById(R.id.timerButton);
    if(task.getStatus() == AsyncTask.Status.RUNNING){
        task.cancel(false);
        task = new CounterTask();
        button.setText("Start");
    }
    else{
        Integer temp = 0;
        task.execute(temp);
        button.setText("Stop");
    }
    System.out.println(task.getStatus());
    }

    private class CounterTask extends AsyncTask {
    @Override
    protected Object doInBackground(Object[] params) {
        for(int counter = 0; true; counter++){
            try{
                publishProgress(counter);
                Thread.sleep(1000);

            }
            catch(InterruptedException exc){
                exc.printStackTrace();
            }
        }
    }

    @Override
    protected void onProgressUpdate(Object[] values) {
        TextView counterView = (TextView)findViewById(R.id.counterTextView);
        counterView.setText(String.valueOf(values[0]));
        System.out.println(values[0]);
    }
    }

}

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lukechenshui.timelapse.MainActivity"
    android:orientation="vertical">

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start"
    android:id="@+id/timerButton"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:clickable="true"
    android:onClick="toggleTimer"
    android:layout_gravity="center_horizontal" />

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/counterTextView"
    android:layout_gravity="center_horizontal" />

</LinearLayout>

示例输出:

//Pressed start
I/System.out: Starting counter!
I/System.out: RUNNING
I/System.out: 0
I/System.out: 1
I/System.out: 2
I/System.out: 3
I/System.out: 4
I/System.out: 5
I/System.out: 6
//Pressed stop
I/System.out: Stopping counter!
I/System.out: PENDING
//Pressed start
I/System.out: Starting counter!
I/System.out: RUNNING
//Pressed stop
I/System.out: Stopping counter!
I/System.out: PENDING

有什么办法可以解决这个问题吗?

最佳答案

我相信 AsyncTask 有一个无限循环并且没有被取消。

您可以将 true 替换为 !isCanceled()。一旦取消,AsyncTask 就应该结束。

您可能还想在停止任务时将其设置为空

关于java - 计数器不会在 AsyncTask 的新实例中重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443041/

相关文章:

android - 如何在加载谷歌地图和添加标记时显示进度条

java - 从另一个线程调用adapter.notifyDataSetChanged()

java - 在 spring view : IllegalStateException: Neither BindingResult nor plain target object 中使用 commandName

java - JDBC 声明表不存在

java - 在 Java 中读取 jar 文件中的 Txt 文件

android - 无法从 Play 商店更新我的应用

java - 创建用户生成的报告

android - DialogFragment 崩溃中的 setRetainInstance

android - android命令行哪里去了?

java - Android等待异步任务完成执行特定方法