Android force close exceptions with thread
Normally, when I close my app I send an intent to my service to signal to safely shutdown using onStartCommand with an extra boolean of true. I do this in my application class' onTerminate. I added the if statements because I was getting a nullptrexception when force closing the app in this block.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
boolean state = intent.getBooleanExtra("terminate", false);
mSafeShutdown = state;
}
else if (mUpdater != null && mUpdater.isRunning()) {
Log.d(TAG, "activity force closed?" +
" Attempting to handle service thread shutdown safely...");
mUpdater.isRunning(false);
try {
mUpdater.join();
} catch (InterruptedException e) {
Log.e(TAG,"Service's UpdaterThread couldn't join");
}
}
return START_STICKY;
}
however, this causes my service to stay alive -
static final int DELAY = 2000;
public void run() {
while (mIsRunning) {
if (!mJobQueue.isEmpty()) {
//do work
}
else if (mSafeShutdown) {
mIsRunning = false;
stopSelf();
}
else {
sleep(DELAY);
}
}
}
The fact that force closing disconnects the debugger its making hard to see exactly whats going on.. Is there a better/safer way to tell my service thread th开发者_运维百科at the application has shut down?
since your thread is a child class, create a method in it to shut it down the thread and call it in your parent class.
An example can be found here http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
精彩评论