My background music service in Android app keeps on playing even when I close the app

前端 未结 1 784
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-28 08:02

I\'m using a background service to run a background music for my app in all of it\'s activities! The issue is that when the app run, it works fine but when I close it it keeps o

相关标签:
1条回答
  • 2021-01-28 08:31

    In the onDestroy() method of your MainActivity you have to stop the service.

    @Override
        protected void onDestroy() {
            super.onDestroy();
            if(isMyServiceRunning(Background_music.class))
            {
                stopService(new Intent(this, Background_music.class));
            }
        }
    
    
    private boolean isMyServiceRunning(Class<?> serviceClass) {
            ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (serviceClass.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
            return false;
        }
    

    Hope this helps you.

    0 讨论(0)
提交回复
热议问题