BackFirej20
2017-01-24 08:26
采纳率: 50%
浏览 2.2k

Android service 判断前台activity

如何在service中判断当前前台运行的是哪个Activity(如果当前应用在前台的话)?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • cloud_do 2017-01-24 08:53
    已采纳

    一般的话,都会自己建立一个activity的管理栈,所有activity都继承BaseActivity, Base中管理入栈出栈,当前前台运行的activity 就是栈顶的那个咯

    打赏 评论
  • stone_you 2017-01-24 09:14
            ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            String activity = am.getRunningTasks(1).get(0).topActivity.getClassName();
    
    
    打赏 评论
  • woqi0025 2017-01-29 15:15

    楼上已经说出了思路了,我这里直接给你帖段代码

     public class ActivityController 
    {
        public static List<Activity> mActivityList = new ArrayList<Activity>();  
        private static Activity mCurrentActivity;  
    
        public static void addActivity(Activity activity) {  
            mActivityList.add(activity);  
        }  
    public static void removeActivity(Activity activity) {  
            mActivityList.remove(activity);  
        }  
    
        public static void setCurrentActivity(Activity activity) {  
            mCurrentActivity = activity;  
        }  
    
        public static Activity getCurrentActivity() {  
            return mCurrentActivity;  
        }  
        public static void finishAll() {  
            for (Activity activity : mActivityList) {  
                if (!activity.isFinishing()) {  
                    activity.finish();  
                }  
            }  
        }  
    
    }
    

    基类在做相应处理就行,然后要获取当前前台Actitivy直接获取mCurrentActivity就行

    打赏 评论

相关推荐 更多相似问题