0

我正在寻找答案,当用户按下设备上的“返回”或“主页”按钮时,如何关闭 MediaPlayer。

当我按返回/主页时出现错误,或者... 按主页时一切正常,但在应用程序恢复时出现错误。谁能帮助我,我找不到任何工作代码:(?

这是我的代码:

package com.gwynbleiddesign.dzwiekizwierzat;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;



public class AnimalDescription extends Activity {

    ImageView animalImage;
    TextView txtNazwa, txtOpisZwierzecia;
    int selectedAnimal = 0;
    MediaPlayer mPlayer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_animal_description);

        Typeface segoeFont=Typeface.createFromAsset(getAssets(),"fonts/segoeprb.ttf");


        txtNazwa = (TextView)findViewById(R.id.txtAnimalName);
        txtNazwa.setTypeface(segoeFont);
        txtOpisZwierzecia = (TextView)findViewById(R.id.txtAnimalDescription);
        txtOpisZwierzecia.setTypeface(segoeFont);
        animalImage = (ImageView)findViewById(R.id.imgAnimalPhoto);

        selectedAnimal = getIntent().getExtras().getInt("selectedAnimal");

        txtNazwa.setText(dane.nazwy[selectedAnimal]+"");
        animalImage.setImageResource(dane.zdjecia[selectedAnimal]);

        mPlayer = MediaPlayer.create(this,dane.dzwieki[selectedAnimal]);

        animalImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

        mPlayer.start();    
            }
        });
    }
     @Override 
        public void onBackPressed(){  
              mPlayer.reset();
              mPlayer.release();
              mPlayer = null;
              super.onBackPressed();
        }

     @Override 
        public void onPause(){

              //mPlayer.reset();
              mPlayer.release();
              mPlayer = null;
              super.onPause();
        }

     @Override 
        public void onStop(){


              mPlayer.reset();
              mPlayer.release();
              mPlayer = null;
              super.onStop(); 
        }
}
4

1 回答 1

0

onCreate如果您是第一次运行您的应用程序,则会调用该方法。如果您关闭它并重新打开它(并且 JVM 没有释放内存)onCreate,则不会再次调用它,因此您的MediaPlayerisnull因为onPause是在活动关闭时触发的。

检查Android Activity Lifecycle并初始化你MediaPlayeronResume

请发布您的Logcat下一次

于 2013-10-18T00:22:41.877 回答