Check if Activity is running from Service

前端 未结 8 458
星月不相逢
星月不相逢 2020-12-02 22:29

How can a Service check if one of it\'s application\'s Activity is running in foreground?

8条回答
  •  甜味超标
    2020-12-02 22:57

    Erian has the correct answer, but its not safe to use "getDefaultSharedPreferences". When you start a Service it use a differente instance that the Activity. Any changes of preferences in the activity, doesnt update the default shared preferences in the Service. So i will change Erian code with ".getSharedPreferences" like this:

    In Activity:

        @Override
        public void onPause() {
            super.onPause();
            getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).edit().putBoolean("isActive", false).commit();;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).edit().putBoolean("isActive", false).commit();
        }
    
        @Override
        public void onResume() {
            super.onResume();
            getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).edit().putBoolean("isActive", false).commit();
        }
    

    In Service:

        if (getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).getBoolean("isActive", false)) {
            return;
        }
    

提交回复
热议问题