2017-08-29 51 views
0

我有一個應用程序,從服務器的響應不同的情況下打開不同的活動。讓我有兩個活動ActivityA & ActivityBAB不能同時啓動。假設A活動被稱爲啓動並在同一時間B也被稱爲啓動。如果A首先啓動,B隱藏它,並開始在視圖的頂部使A在背景中。我如何檢查A是否已從內部啓動活動B ??Android - 如何獲得Android上的最後前景活動?

到現在我曾嘗試:

ActivityManager m = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); 
    List<ActivityManager.RunningTaskInfo> runningTaskInfoList = m.getRunningTasks(10); 
    Iterator<ActivityManager.RunningTaskInfo> itr = runningTaskInfoList.iterator(); 
    while (itr.hasNext()) { 
     ActivityManager.RunningTaskInfo runningTaskInfo = (ActivityManager.RunningTaskInfo) itr.next(); 
     int id = runningTaskInfo.id; 
     CharSequence desc = runningTaskInfo.description; 
     int numOfActivities = runningTaskInfo.numActivities; 
     String topActivity = runningTaskInfo.topActivity.getShortClassName(); 
     Constants.debugLog(TAG, "checkActivityStack desc: " + desc + " numOfActivities: " + numOfActivities + " topActivity: " + topActivity); 
    } 

========================= 另一個從堆棧

ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE); 

    int sizeStack = am.getRunningTasks(5).size(); 

    for(int i = 0;i < sizeStack;i++){ 
     ComponentName cn = am.getRunningTasks(2).get(i).topActivity; 
     Constants.debugLog(TAG, "checkActivityStack "+cn.getClassName()); 
    } 
+0

採取全局變量定義在應用程序類,把它寫在一個活動啓動,並檢查變量b活動 – Reena

+0

你可以發佈你的代碼,女巫打開這些活動? – Hamza

+0

,否則您需要檢查活動管理器的運行進程 – Reena

回答

1

,我可能會做一個公共領域,代碼將是這個樣子:

// A 
public static boolean started = false; 

@Override 
public void onStart() { 
    super.onStart(); 
    started = true; 
} 

@Override 
public void onStop() { 
    super.onStop(): 
    started = false; 
} 

,並檢查是這樣的:

// B 
if (A.started) { 
    // Abort starting 
} 
+0

實際上,我並不想這樣做。如果不知何故,我可以得到最後的前景活動名稱的名稱這將是一個很大的幫助對我來說 –

+0

,但如果我沒有找到任何解決方案,我一定會用這種方式 –

1

我不確定這是不是你要找的東西,但它看起來很簡單。 http://iamvijayakumar.blogspot.com/2011/09/get-current-activity-and-package-name.html

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); 
    List<RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
    ComponentName componentInfo = taskInfo.get(0).topActivity; 
    Log.d(WebServiceHelper.TAG, "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName() + " Package Name : " + componentInfo.getPackageName()); 

你需要使用許可android.permission.GET_TASKS 希望這有助於

+0

這一個返回我當前頂級活動的名稱,但我希望最後一個在當前開始的背景中 –

+0

確定未使用am.getRunningTasks(10);爲最後10個活動並且然後使用循環 –

+0

Iterator itr = runningTaskInfoList.iterator(); (itr.hasNext()) { RunningTaskInfo runningTaskInfo =(RunningTaskInfo)itr.next(); int id = runningTaskInfo.id; CharSequence desc = runningTaskInfo.description; 字符串topActivity = runningTaskInfo.topActivity。getShortClassName(); int numOfActivities = runningTaskInfo.numActivities; } –