4

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;
            }
        }
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104

1 Answers1

3

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.

Sam M
  • 640
  • 1
  • 8
  • 18
  • Oh, I've really missed the datetime stamp, sorry about that :) – VMAtm Mar 31 '16 at 13:50
  • Hi, where do I put the above code? do I put in within my class MainActivity? – Khalil Khalaf Apr 03 '16 at 00:54
  • `YourTask` is a class, so you have to create the separate file or mark it as `private`, I think – VMAtm Apr 04 '16 at 14:19
  • 1
    YourTask is a class like VMAtm says. Create a new YourTask object and use the execute function where this code is `Task.Run(() = > Process(), CancelationToken.Token); //start a method on another thread }` – Sam M Apr 04 '16 at 17:59