Issue
I want to click the 'start' button so that the app can start and run two services at the same time.
I have created two services named ServiceA
and ServiceB
. For each service, I've
created a runnable method (in onStartCommand
) to escape the ANR problem. I also created a start button, so that when I click the start button, I hope that ServiceA
and ServiceB
can start at exactly the same time, or in other words, synchronize.
I've tried many ways. The first attempt is simply to start the services one by one, but that failed:
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent1 = new Intent(MainActivity.this, ServiceA.class);
startService(intent1);
Intent intent2 = new Intent(MainActivity.this, ServiceB.class);
startService(intent2);
}
});
Then I am planning to try AsyncTask
, but as the services are run in the background with a handler, if I use AsyncTask
it will create another background handler, which is not applicable. Do you have any suggestions to run two services in one button click at exactly the same time?
Solution
You need to look into java concurrency and multi-threading. If you wish to run the two methods side by side, you must use threads...
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
codeHereWillRunConcurrentlyWithMainThread();
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
codeHereWillAlsoRunConcurrentlyWithMainThread();
}
});
thread2.start();
However, if your two threads are supposed to be working together, you need to look up how to use java's built in "synchronize" keyword. It is used to prevent deadlocks in multi-threaded concurrent environments and prevent a variable/variables from being modified while other threads are operating on said variable/variables.
For more info: https://docs.oracle.com/javase/tutorial/essential/concurrency/ http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ http://www.vogella.com/tutorials/JavaConcurrency/article.html
Answered By - Joe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.