Android强制关闭线程异常

时间:2011-03-31 18:05:44

标签: android multithreading service shutdown

通常情况下,当我关闭我的应用程序时,我会向我的服务发送一个意图,使用onStartCommand以及额外的布尔值true来安全关闭。我在我的应用程序类'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);
        }
    }
}

强制关闭会断开调试器的连接,这使得很难看到发生了什么。是否有更好/更安全的方式告诉我的服务线程应用程序已关闭?

1 个答案:

答案 0 :(得分:1)

因为你的线程是子类,所以在它中创建一个方法来关闭它并在你的父类中调用它。

这里有一个例子 http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html