2011-03-31 115 views
0

正常情況下,當我關閉我的應用程序時,我發送一個意向到我的服務,以使用帶有額外布爾值true的onStartCommand安全關閉。我在我的應用程序類'onTerminate中執行此操作。我添加了if語句,因爲當強制關閉此塊中的應用程序時,我收到了nullptrexception。Android強制關閉線程異常

@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); 
     } 
    } 
} 

是強制關閉斷開其使得很難看到究竟怎麼回事..有沒有更好/更安全的方式調試器的事實告訴我的服務線程應用程序已關閉?

+0

「我做這在我的應用程序類的onDestroy」 ......除非你有不同的文檔對我來說,Android應用程序類不具有的onDestroy()方法。另外,你爲什麼'強行關閉'? – Squonk 2011-03-31 18:18:12

+0

@MisterSquonk:我的意思是關於終止,我說錯了。很多人喜歡強制關閉他們的應用程序,因爲他們相信它可以節省大量的電池壽命。我對社會認爲的方式不負責任! – 2011-03-31 18:59:28

回答

1

由於您的線程是一個子類,因此在其中創建一個方法將其關閉並在父類中調用它。

一個例子可以在這裏找到 http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

+0

我讓mSafeShutdown成爲updaterThread的成員,而不是修復它的服務。然而,我偏愛這篇文章,因爲我得到了我需要修復的信息,當我回去清理。謝謝。 – 2011-03-31 20:40:09