2016-09-27 32 views
0

想象這種堆棧情況: A - B- C - D - B,A,B和C是活動,但D是服務。重複使用相同的活動

基本上,我有一個服務(D),並從那個服務我想調用一個已經存在的活動(B)。我知道如果我想重新使用一個活動,我所要做的就是使用標誌(或者更改清單)SingleTop(如果它已經在頂部將重新使用該活動)或SingleTask (將重新使用該活動是否處於最佳狀態)。

問題是,因爲我在一個服務中,我將不得不添加標誌FLAG_ACTIVITY_NEW_TASK,以便我可以調用一個活動。另外,我在我的清單中添加了SingleTask作爲啓動模式,以便該活動將被重新使用。

這很好,因爲它重新使用相同的活動並返回到onNewIntent(意圖意圖)方法。 問題是,我把所有的東西都作爲一個額外的意圖來作爲null。我嘗試通過該意圖發送2個字符串和2個布爾值,並且它們都以空值到達onNewIntent(意圖意圖)。

我該如何解決這個問題?在獲得額外資訊之前,我必須在onNewIntent(Intent intent)方法中做些什麼嗎?有沒有更好的選擇?

PS: 我聽說過StartActivityForResult或類似的東西。這隻能工作50%的時間,因爲這是一個「類似聊天」的應用程序。

所以我會在「聊天」中,從我去哪裏去另一個活動,在那裏我可以選擇要發送的東西。在那之後,我會去完成轉移的服務,然後回到「聊天」。 但是當我收到一些東西時,我已經在「聊天」中了,所以startActivityForResult在這種情況下不起作用(要接收的服務將在後臺運行+我不想完成接收部分,因爲我想總是在聽某些東西)。

下面是該服務的代碼,我嘗試重新啓動單一活動:

 Intent transfRec=new Intent(ServerComm.this ,TransferRecordActivity.class); 
          transfRec.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

          transfRec.putExtra("receivedFilePath",appName+".apk"); 
          transfRec.putExtra("joinMode","appselection"); 
          transfRec.putExtra("nameOfTheApp",appName); 
          transfRec.putExtra("received",false); 

          transfRec.putExtra("isHotspot",isHotspot); 
          startActivity(transfRec); 

這裏是我的onNewIntent的代碼(意向意圖):

protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); 

    System.out.println("I am here in the new intent"); 
    if(intent==null){ 
     System.out.println("Intent is null inside the new intent method !!!"); 
    } 
    tmpFilePath=getIntent().getStringExtra("receivedFilePath"); 
    System.out.println("The tmpFilePath is : "+tmpFilePath); 
    received=getIntent().getBooleanExtra("received",true); 
    nameOfTheApp=getIntent().getStringExtra("nameOfTheApp"); 
    isHotspot=getIntent().getStringExtra("isHotspot"); 
    System.out.println("O received boolean esta a : : : "+received); 
    textView.setVisibility(View.GONE); 

    receivedFilePath= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+tmpFilePath; 
    System.out.println("transfer REcord Activity _: the received file path is :::: " +receivedFilePath); 

    getReceivedApps(); 

    adapter= new HighwayTransferRecordCustomAdapter(this,listOfItems); 
    receivedAppListView.setAdapter(adapter); 

編輯:正如你們可以看到我檢查意圖是否爲空,而事實並非如此,因爲它沒有執行system.out.println這個條件!

回答

1

問題是您在onNewIntent()內撥打getIntent()。來自getIntent()的文檔:

返回開始此活動的意圖。

因此,你得到提供給onCreate()intent。爲了獲得提供給onNewIntent()intent,您只需使用intent這是在方法簽名提供:

protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); 
    tmpFilePath=intent.getStringExtra("receivedFilePath"); 
    ... 
} 
+0

謝謝哥哥。現在我解決了這個問題,但是這些東西仍然沒有加載。它們不是null,但是listview不會「刷新」或者不顯示它顯示的項目。你認爲我應該問另一個問題,或者只是改變這個問題? –

+0

是的,請這樣做,因爲這個問題與您的原始查詢無關。 – Shaishav

+0

是的,謝謝你,兄弟,我會做到的。 –