在Android中,与C#的AsyncTask相当的是什么?如何强制停止它?

4
以下C#例程可启动/停止/重新启动不同线程上的函数:
    using System.Threading;
    using System.Threading.Tasks;

    namespace ConsoleApplication3
    {
        class Program
        {
            static void Main(string[] args)
            {
                var CancelationToken = new CancellationTokenSource(); // declare and initialize a token for the cancelaion

                while (SomeCondition)
                {
                    CancelationToken = new CancellationTokenSource(); // re initialize if wanted to restart
                    Task.Run(() = > Process(), CancelationToken.Token); //start a method on another thread
                }
                CancelationToken.Cancel(); //stop the task
            }

            public static void Process()
            {
                while (true) // Keep running forever on the new thread
                { } // some functionality goes here
            }
        }
    }

所以,我希望有一个在不同线程上永久运行的函数,并且我想能够在不同线程上启动、停止和/或重新启动它。什么是与Android Studio Java的这个例程完全等效的东西?
我尝试下面的代码,认为它会做相当的工作。但我遇到了错误:
Class MyTast my either be declared abstract or implement abstract method 

为什么这个不起作用?

代码:

public class MainActivity extends AppCompatActivity 
{
        protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);

               Button StrtBtn = (Button) findViewById(R.id.StartButton);
               Button StpBtn = (Button) findViewById(R.id.StopButton);

               // Start Button Click
               StrtBtn.setOnClickListener(
                      new Button.OnClickListener() {
                          public void onClick(View v) {
                                 // I want to start the function on another thread here
                            }//onClick
                       }//onClickListener
               );//setOnClickListener


              // Stop Button Click
              StpBtn.setOnClickListener(
                    new Button.OnClickListener() {
                        public void onClick(View v) {
                             // I want to stop the function here
                         }//onClick
                     }//onClickListener
              );//setOnClickListener

        public void MyFunction()
        {
            \\ my function
        }
}

public class MyTask extends AsyncTask<String, int, Void>{

    protected void doInBackground(){
        while(true){
            // my code here to call the function here

            if(isCancelled()){
                break;
            }
        }
    }
}

可能是 Android - Cancel AsyncTask Forcefully 的重复问题。 - VMAtm
如果我成功实现AsyncTask,那么我会使用您的方法来强制取消它。然而,这篇帖子本身并没有回答我的问题,抱歉并感谢。 - Khalil Khalaf
没问题 - 这是一个“可能”的重复 :) - VMAtm
@VMAtm,您能否看一下已编辑的内容?:( - Khalil Khalaf
你没有在任务方法 doInBackground 上标记 @Override 标志。 - VMAtm
1个回答

3
你应该尝试使用AsyncTask。虽然这比C#更费力,但这就是Java的特点。 http://developer.android.com/reference/android/os/AsyncTask.html 编辑
public class YourTask extends AsyncTask<ArgumentType,null, valueToReturn>{

protected valueToReturn doInBackground(ArgumentType..args){
        while(true){
            //your code here 

            if(isCancelled()){
                            return null;
                    }
        }
    }

}

在你的主程序中,你可以这样调用:
YourTask task = new YourTask();
task.execute(args);

您可以调用。
task.cancel(true);

结束任务。注意,true表示如果正在运行,则任务将被中断。

我不会为你编写所有代码并测试它,但这应该足以让你开始。Java没有提供太多出色的异步功能。


哦,我真的错过了日期时间戳,对此感到抱歉 :) - VMAtm
嗨,我应该把上面的代码放在哪里?是放在我的 MainActivity 类中吗? - Khalil Khalaf
"YourTask" 是一个类,因此您必须创建单独的文件或将其标记为“private”。 - VMAtm
1
YourTask是一个像VMAtm说的类。创建一个新的YourTask对象,并使用execute函数,在这段代码中Task.Run(() = > Process(), CancelationToken.Token); //start a method on another thread} - Sam M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接