2014-11-02 58 views
0

我有一個類,它在後臺執行一些命令。 Class方法是異步執行的(通過使用AsyncTask),當命令完成時,它將命令結果發送到事件。然後,開始新的活動。爲此,我在OnCreate方法中添加了MainActitity:Android - 使用來自AsyncTask的新數據刷新運行活動結果

ssh = new SshSupport(); 
ssh.Connect(); 
ssh.ExecuteCommand(commandType); 
//.................................. 
ssh.eventHandler = new ISshEvents() 
{ 

    @Override 
    public void SshCommandExecuted(SshCommandsEnum commandType, String result) 
    { 
    if (progressDialogExecuting.isShowing()) progressDialogExecuting.dismiss(); 

    Intent intent = new Intent(MainActivity.this, ResultListActivity.class); 
    intent.putExtra("result", result); 
    intent.putExtra("commandType", commandType); 
    startActivity(intent); 
    } 

所以它的工作原理應該如此。我的命令在後臺啓動,完成後,我的事件觸發並顯示帶有結果的新活動(所有結果都通過getIntent()。getExtras()接收,然後格式化爲顯示)。

問題:在結果活動我有「刷新」按鈕。按下時,所有數據都應刷新。所以我需要再次執行ssh.ExecuteCommand(commandType);才能刷新數據。請注意,我不想爲此打開新的ssh連接。相反,我想使用已經打開的連接,並再次執行我的命令。 所以我做了我的'ssh'靜態和我用MainActivity.ssh.ExecuteCommand(commandType);刷新按鈕按下。它可以工作,但很明顯,它會導致創建ResultListActivity的第二個實例,而不是刷新現有數據。

我甚至可以通過檢查它是否已經存在(例如,通過添加'active'布爾型靜態變量)來避免再次創建結果活動。但是,它不會幫助我,因爲我現在還沒有任何可能刷新現有活動中的數據。

那麼,我該怎麼做呢?我現在被卡住了...你有什麼想法嗎?

回答

0

沒有迴應,所以我回答了我自己的問題。我的解決辦法是: - 我的活動launchMode更改爲singleTop - 覆蓋方法onNewIntent

在這種情況下,每次啓動這個活動:如果活動已經存在,它不會被重新創建。相反,onNewIntent方法將被調用。

http://developer.android.com/guide/topics/manifest/activity-element.html#lmode http://developer.android.com/reference/android/app/Activity.html#onNewIntent%28android.content.Intent%29

不過,我不知道這樣的做法是很好的。你怎麼想?