How to stop all workflows in an Android application

How to stop all current workflows in an Android application without stopping the main thread?

Any example for this?

+8
source share
4 answers

Actually the thread has a stop() method, so you can view all the worker threads and call this method for each of them.

Question: "Where to get a list of workflows?" The best solution is to store this list somewhere at the application level, i.e. Each time you create a workflow, put it in a special list. This is the best solution, because you and only you know that the thread is a "work" thread.

But theoretically, you can even dynamically detect your application and get streams. There is a static method Thread.enumerate(Thread[] threads) that populates the provided array. But how do you know how many threads are working now? Use Thread.activeCount() .

 Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads); for (Thread t : threads) { if (isWorkerThread(t)) { t.stop(); } } 

You must define your workflows. For example, you can use a stream name or a thread stack trace for this.

BUT it is a crime to call the deprecated stop() method. Please refer to the javadoc of this method for reasons.

The "right" method is to implement an elegant shutdown mechanism at the application level. Each thread should check some flag, which says whether the thread should turn off, and when the flag is true, just return from the run() method. In this case, it is very simple to close worker threads: just set the value of this flag to true and the threads will stop. That's the right decision.

+3
source

This post tells a ton about threads, please read and submit if this does not answer your question.

Stop / kill a stream

+2
source

in java, do not provide a method to stop the thread.

you can only interrupt stream, but the stream must be in a state that can be interrupted, for example, sleep , wait , etc.

, or you can use some tricks to rule out a thread exception , for example:

1. if the stream is connected to the network, you want to stop the stream, you can close the network connection, throw an ioexception;

2. If the stream is read in a file, you can close the stream to throw an ioexception;

3. If the thread requests a database, you can close the database

therefore it depends on your work.

+2
source

There are two ways to do this.

Break Themes

  Thread.interrupt() 

Does this solve the problem? No, it is not. A thread will only be interrupted if it is in a block / wait state. Calling thread.interrupted does not stop the thread. Then how will this help? The code you are trying to run. Check for operations such as long network operations, database operations. This way you can interrupt most threads.

Kill the process and restart it.

  Kill the app process and restart it from zygote (It might not be for all devs) 
0
source

Source: https://habr.com/ru/post/910691/


All Articles