关闭应用程序时如何停止声音

时间:2016-12-26 19:29:06

标签: java android audio background media-player

关闭应用程序时,我无法停止声音/声音。按后退按钮。声音在后台播放,而不是任何小部件停止声音所以这些是我的代码。如何解决这个问题。我需要什么?  谢谢:))

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();

        }   });  

2 个答案:

答案 0 :(得分:0)

要将应用程序发送到后台时将 MediaPlayer 静音,您可以在应用中的每项活动onPause()onStop()上调用此代码:

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;
            }
        }
    }
}

我希望这可以帮到你

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

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

答案 1 :(得分:-1)

您必须覆盖活动的onPause()

在您的活动类中编写此代码...

 @Override
    protected void onPause()
    {
       super.onPause();
       if(s1.isPlaying()){
            s1.stop();
            s1.release();
            }
       if(s2.isPlaying()){
            s2.stop();
            s2.release();
            }
    }