What is equivalent to C# AsyncTask in Android? And how to force stop it?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 15:34:31

问题


the below routine on C# starts/stops/restarts a function on a different thread:

    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
            }
        }
    }

So, I want a forever-running function on a different thread and I want to be able to start it, stop it and/or restart it, all on a different thread. What is the exact equivalent of this routine for Android Studio Java?

I am trying the below thinking it would do the equivalent. But I get error:

Class MyTast my either be declared abstract or implement abstract method 

Why this is not working?

Code:

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;
            }
        }
    }
}

回答1:


You should try using AsyncTask. Its going to be more work than C# but thats java for you.

http://developer.android.com/reference/android/os/AsyncTask.html

EDIT

public class YourTask extends AsyncTask<ArgumentType,null, valueToReturn>{

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

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

}

in your main you can call do something like this

YourTask task = new YourTask();
task.execute(args);

you can call

task.cancel(true);

to end the task. Note that true tells the task to interupt if running

I'm not going to write all the code for you and test it but this should be enough for you to get going. Java doesn't provide a lot of great async functionality.



来源:https://stackoverflow.com/questions/36321684/what-is-equivalent-to-c-sharp-asynctask-in-android-and-how-to-force-stop-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!