Android强制关闭线程异常
通常,当我关闭应用程序时,我会向我的服务发送一个意图,以使用带有额外布尔值 true 的 onStartCommand 发出安全关闭信号。我在我的应用程序类的 onTerminate 中执行此操作。我添加了 if 语句,因为在强制关闭此块中的应用程序时,我收到了 nullptrException。
@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;
}
但是,这会导致我的服务保持活动状态 -
static final int DELAY = 2000;
public void run() {
while (mIsRunning) {
if (!mJobQueue.isEmpty()) {
//do work
}
else if (mSafeShutdown) {
mIsRunning = false;
stopSelf();
}
else {
sleep(DELAY);
}
}
}
强制关闭会断开调试器的连接,这使得很难准确地看到正在发生的情况。是否有更好/更安全的方法来告诉我的服务线程应用程序已关闭?
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 that the application has shut down?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的线程是子类,因此在其中创建一个方法来关闭线程并在父类中调用它。
可以在这里找到一个例子
http://download.oracle.com/javase/1.4 .2/docs/guide/misc/threadPrimitiveDeprecation.html
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