2016-12-02 63 views
1

在我的靜態方法(參數只有一個字符串),我想使用對話框(new AlertDialog.Builder(mContext)),但對話框需要一個活動上下文來構造。如果我不通過外部上下文參數,只通過反射或其他方法,如何獲得當前最高活動的對象?如何獲得當前頂級活動上下文

public static Activity getActivity() { 
    Class activityThreadClass = null; 
    try { 
     activityThreadClass = Class.forName("android.app.ActivityThread"); 
     Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null); 
     Field activitiesField = activityThreadClass.getDeclaredField("mActivities"); 
     activitiesField.setAccessible(true); 
     Map activities = (Map) activitiesField.get(activityThread); 
     for (Object activityRecord : activities.values()) { 
      Class activityRecordClass = activityRecord.getClass(); 
      Field pausedField = activityRecordClass.getDeclaredField("paused"); 
      pausedField.setAccessible(true); 
      if (!pausedField.getBoolean(activityRecord)) { 
       Field activityField = activityRecordClass.getDeclaredField("activity"); 
       activityField.setAccessible(true); 
       Activity activity = (Activity) activityField.get(activityRecord); 
       return activity; 
      } 
     } 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } catch (NoSuchMethodException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
     e.printStackTrace(); 
    } catch (NoSuchFieldException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

我用這個代碼,但是當我打電話在非活動類這種方法,activities爲空。

有沒有其他辦法?不能使用對話框,只要能夠彈出用戶可以看到的信息即可。點限制:不從參數獲取上下文。

+0

它看起來像你倒退這個問題。不要試圖找到頂部的Activity,你應該調用Activity中的Dialog。不要打架。你試圖做什麼?爲什麼你需要首先找到頂級的Activity? – Bryan

回答

2

使用Application.ActivityLifecycleCallbacks

實現的例子:

class ActivityLifeCycleCallbackImpl implements Application.ActivityLifecycleCallbacks { 

    private Set<Activity> set = new HashSet<>(); 


    @Override 
    public void onActivityStarted(Activity activity) { 
     set.add(activity); 
    } 

    @Override 
    public void onActivityStopped(Activity activity) { 
     set.remove(activity); 

    } 

    Activity getCurrentActivity() { 
     if (set.isEmpty()) { 
      return null; 
     } 
     return set.iterator().next(); 
    } 


} 

,並在您的自定義應用程序類:

ActivityLifeCycleCallbackImpl activityLifeCycleCallback = new ActivityLifeCycleCallbackImpl(); 
    @Override 
    public void onCreate() { 
     registerActivityLifecycleCallbacks(activityLifeCycleCallback); 

} 
+0

ActivityLifeCycleCallbackImpl可以解決我的問題〜謝謝 – Gaga