Reputation: 37
I have a project which need to update the vehicle lat-lnt by an thread looping pull an Api in a Map view.And i hope that the updateThread can sleep when app gose onStop or onPause,Wake up When OnResume and aslo Never be killed in app life cycle; First time,i try to just use below (solution 1) to updateing:
new Thread(new Runnable() {
@Override
public void run() {
while(true){
//update-Vehicle-Looping
}
}
}).start();
However during testing,i found that Threads are not automatically killed when the app goes to onStop or onPause, however, there is no guarantee it won't be killed,Android will keep it running until it needs the resources that the thread is using.This not will make a big resources cost but also have a thread-killed risk;
So i try to use an alternative (Solution2) whick can control the thread in it lift cycle;
HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
mHandler = new Handler(thread.getLooper());
mHandler.post(UpdateRunable);
Runable UpdateRunable=new Runnable() {
@Override
public void run() {
while(IsRun){
//update-Vehicle-Looping
}
}
};
use IsRun to control the update thread awaker or sleep in app lift cycle;In a sense(Solution 2) improve (solution 1). but can't avoid thread-killed risk.
Can any body give me some suggestion to control the update thread in app life cycle?
Upvotes: 0
Views: 60
Reputation: 616
You should use handler with Runable interface as you are updating ui. while you are in onstop stage of activity life cycle you should not post any message to handler as your app will get crashed.
Upvotes: 0
Reputation: 3282
You should move your logic in a Service so it will not depend on Activity's lifecycle first. Doing that you can just stop dispatching your events to map view. Use Service binding to control your UI from service
Upvotes: 0