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