Method unnecessarily getting called?

后端 未结 2 1488
旧巷少年郎
旧巷少年郎 2021-01-16 20:30

I have a BaseActivity that gets extended by every other activity. The thing is, I have the music muted whenever the user leaves (onPause) the activity. I also stop listening

2条回答
  •  余生分开走
    2021-01-16 21:24

    From my understanding you are muting your music playing in onPause of BaseActivity, instead of that write it inside your Music play activity

    Ex :

     public class BaseActivity extends AppCompatActivity{
    
         @Override
         public void onPause(){
          //do things that common for all activities
         }
        }
    
    
    public void MusicPlayActivity extends AppCompatActivity{
    
     @Override
     public void onPause(){
     music.mute()
     }
    }
    

    This will work

    UPDATE

    There are few ways to detect whether your application is running in the background, but only one of them is completely reliable: Track visibility of your application by yourself using Activity.onPause, Activity.onResume methods. Store "visibility" status in some other class.

    Example : Implement custom Application class (note the isActivityVisible() static method):

    public class MyApplication extends Application {

      public static boolean isActivityVisible() {
        return activityVisible;
      }  
    
      public static void activityResumed() {
        activityVisible = true;
      }
    
      public static void activityPaused() {
        activityVisible = false;
      }
    
      private static boolean activityVisible;
    }
    

    Register your application class in AndroidManifest.xml:

    
    

    Add onPause and onResume to every Activity in the project (you may create a common ancestor for your Activities if you'd like to, but if your activity is already extended from MapActivity/ListActivity etc. you still need to write the following by hand):

    @Override
    protected void onResume() {
      super.onResume();
      MyApplication.activityResumed();
    }
    
    @Override
    protected void onPause() {
      super.onPause();
      MyApplication.activityPaused();
    }
    

    ActivityLifecycleCallbacks were added in API level 14 (Android 4.0). You can use them to track whether an activity of your application is currently visible to the user. Check Cornstalks' answer below for the details.

提交回复
热议问题