2014-04-30 35 views
1

我有一個通過藍牙接收消息的Android應用程序(但該部分在此不相關)。處理程序收到這些信息。當它被Android任務管理器殺死之後啓動應用程序時,它應該像它應該那樣工作。如果我沒有殺死它,只是把它拿回來,它不會像它應該那樣。該代碼非常簡單:恢復行爲後的Android處理程序

public class MainActivity extends Activity 
{ 

private BtBase mBtBase; 
private TextView mTvBluetooth; 
private View mView; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    mBtBase = BtBase.getInstance(this, mHandler); 
    setContentView(R.layout.bluetooth); 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    mTvBluetooth = (TextView) findViewById(R.id.tvBluetooth); 
    if(mBtBase.getErrorCode() == BtLibraryConstants.BT_CONNECTED) 
    { 
     mTvBluetooth.setText("Text 1"); 
    } 
    else 
    { 
     mTvBluetooth.setText("Text 2"); 
    } 

} 


private final Handler mHandler = new Handler() 
{ 
    @Override 
    public void handleMessage(Message msg) 
    { 
     switch(msg.what) 
     { 
     case 0: 
      if(msg.arg2 == 0) 
      { 
       Toast.makeText(getApplicationContext(), "Text 1", Toast.LENGTH_LONG).show(); 
       mTvBluetooth.setText("Text 1."); 
      } 
      else if(msg.arg2 == 1) 
      { 
       Toast.makeText(getApplicationContext(), "Text 2", Toast.LENGTH_LONG).show(); 
       mTvBluetooth.setText("Text 2"); 
      } 
      break; 
     case 1: 
      Toast.makeText(getApplicationContext(), (String) msg.obj, Toast.LENGTH_LONG).show(); 
      mTvBluetooth.setText("Text 3: " + (String) msg.obj); 

      break; 
     default: 

     } 
    } 
}; 
} 

什麼從恢復情況開始應用後不工作:

  • 在處理程序敬酒的消息顯示正確
  • 中的onResume TextView的具有正確的值根據國家

什麼從恢復情況開始應用後不工作:

  • 處理程序中的文本視圖更新不起作用。

請記住,吐司工作正常,所以代碼被執行。請記住,它在任務管理器中殺死應用程序後可以正常工作,所以它不是完全錯誤的。我認爲它有一些與生命週期管理相關的事情。

我試過幾件事情

  • 通過主尺蠖進入處理程序,但自從我創建從主線程處理它不應該是必要的
  • 得到了主視圖和無效它處理程序強制重繪

既沒有工作,但我當然可能在這些嘗試中做了錯誤的事情。

調試器顯示我的textView mTvBluetooth不爲null,它看起來像是我正在尋找的那個。但也許一個新的mTvBluetooth以某種方式創建,我正在使用舊的mTvBluetooth。

最後但並非最不重要的logCat不顯示任何錯誤。

+0

什麼是BtBase? – ben75

+0

我需要藍牙通信的一個對象。這需要我的處理程序發送消息。我不認爲這是相關的,因爲處理程序被召喚,吐司出現。 – AndyAndroid

+0

檢測到處理程序泄漏。你也應該確保Handler的Looper是主要的Looper。 –

回答

0

嘗試

mTvBluetooth = (TextView) findViewById(R.id.tvBluetooth);

onResume()移動此代碼到onCreate()方法。也許它有幫助。

此外,當以常見方式恢復活動時,不會重新創建TextView。 但有時它可以被摧毀購買系統獲得更多的內存。在這種情況下,當您恢復活動時,方法onCreate必須在onResume之前調用。

如果您不想移動代碼,請嘗試使mTvBluetooth volatile。 嘗試在調試時查看mHandler和onResume()中的mTvBlutooth值。 在eclipse中使用「Inspect」工具(Ctrl + Shift + I),你會看到一個變量id,例如: 830032407656.在這兩個時刻檢查ID。

請留下評論是有幫助的。