-1

I can not stop the sound/ sounds when I close the app.or press the back button. Sound is playin in background and not any widget to stop sound so these are my codes. how to fix it isue. and what I need? Thanks :)

public class MainActivity extends AppCompatActivity {

   MediaPlayer s1;  Button agackakan;
   MediaPlayer s2;  Button getCam_bastankarasi;



  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView (R.layout.activity_main);



        s1 = MediaPlayer.create(MainActivity.this,ormann_agackakani_taklama);
        s2 = MediaPlayer.create(MainActivity.this, R.raw.cam_bastankarasi);


    agackakan=(Button) findViewById ( R.id.agackakan);
    getCam_bastankarasi= (Button) findViewById (R.id.cambastankarasi);


    agackakan.setOnClickListener(new View.OnClickListener () {
        @Override
        public void onClick(View v) {
            s1.start();

        }   });   

    getCam_bastankarasi.setOnClickListener(new View.OnClickListener () {
        @Override
        public void onClick(View v) {
            s2.start();

        }   });  
serif
  • 21
  • 7

2 Answers2

0

To mute MediaPlayer when your application is sent to background, you can call this code on onPause() or onStop() on every activity in your application:

public static void muteIfSentToBackground(final Context context) {
        ActivityManager am = (ActivityManager)     context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            if(s1 != null){
                s1.stop();
                s1.release();
                s1 =null;
            }
            if(s2 != null){
                s2.stop();
                s2.release();
                s2 = null;
            }
        }
    }
}

I hope this can help you

    @Override
    protected void onPause() {
        super.onPause();
        muteIfSentToBackground(this);}

    @Override
    protected void onStop() {
        super.onStop();
            muteIfSentToBackground(this);}
ucMedia
  • 1
  • 1
-1

you have to override the onPause() of the activity

write this code in your activity class...

 @Override
    protected void onPause()
    {
       super.onPause();
       if(s1.isPlaying()){
            s1.stop();
            s1.release();
            }
       if(s2.isPlaying()){
            s2.stop();
            s2.release();
            }
    }
rafsanahmad007
  • 23,062
  • 6
  • 43
  • 58