如何在Java Android Studio中的新线程上启动进程? (要求相当于C#代码)

我在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 (something) { if (Whatever) { CancelationToken = new CancellationTokenSource(); // re initialize if wanted to restart Task.Run(() = > Process(), CancelationToken.Token); //start a method on another thread } else 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 的这个例程确切等价物是什么?

以下是我在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{ protected void doInBackground(){ while(true){ // my code here to call the function here if(isCancelled()){ break; } } } } 

您应该尝试使用AsyncTask。 它将比C#更多的工作,但这对你来说就是java。

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

编辑

 public class YourTask extends AsyncTask{ protected valueToReturn doInBackground(ArgumentType..args){ while(true){ //your code here if(isCancelled()){ return null; } } } } 

在你的主要你可以打电话做这样的事情

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

你可以打电话

 task.cancel(true); 

结束任务。 请注意,如果正在运行,则告诉任务中断

我不打算为你编写所有代码并测试它,但这应该足以让你开始。 Java没有提供很多很棒的异步function。

Interesting Posts