应用程序恢复时如何防止onCreate?

时间:2016-06-19 01:29:28

标签: android android-mediaplayer oncreate

我制作了一个音乐播放器usim MediaPlayer。当我关闭应用程序时,歌曲继续播放但是当我恢复时,onCreate被称为一切都重新开始,之前的歌曲也在继续播放。因此,如果现在我开始新歌,即使只有一个MediaPlayer变量,这两首歌也会播放。为什么在重新打开应用程序时调用onCreate。有什么方法可以预防呢?

编辑:请注意,xml文件也会重置。在离开应用程序之前,我放松了对歌曲播放的控制。

public class MainActivity extends AppCompatActivity {

SeekBar seekBar;
MediaPlayer mediaPlayer;
ImageView imageView;
Handler handler = new Handler();
private String[] mAudioPath;
private String[] mMusicList;
static int i = 0;

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

    final Button ctrl = (Button) findViewById(R.id.play);
    Button stop = (Button) findViewById(R.id.stop);
    imageView = (ImageView) findViewById(R.id.imageView);
    ListView listView = (ListView) findViewById(R.id.listView);
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.song);
    seekBar.setMax(mediaPlayer.getDuration());

    //get tracks list
    mMusicList = getAudioList();
    mAudioPath = getmAudioPath();

    ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mMusicList);
    listView.setAdapter(mAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //Toast.makeText(MainActivity.this,mAudioPath[position],Toast.LENGTH_SHORT).show();
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(mAudioPath[position]);
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
                seekBar.setMax(mediaPlayer.getDuration());
                seekBar.setProgress(0);
                ctrl.setText("║");
                try {
                    byte[] art;
                    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                    mediaMetadataRetriever.setDataSource(mAudioPath[position]);
                    art = mediaMetadataRetriever.getEmbeddedPicture();
                    Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
                    imageView.setImageBitmap(songImage);
                }
                catch (Exception e){
                    byte[] art;
                    Bitmap songImage = BitmapFactory.decodeResource(getResources(), R.drawable.default_artwork);
                    imageView.getLayoutParams().width= ViewGroup.LayoutParams.MATCH_PARENT;
                    imageView.setImageBitmap(songImage);
                }
                mediaPlayer.start();
                handler.postDelayed(runnable,1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
});

    //Get track data
    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
    mediaMetadataRetriever.setDataSource(MainActivity.this, Uri.parse("android.resource://in.swapsha96.playtime/"+R.raw.song));
    String artist;
    artist = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
    if (artist == null)
        artist = "Unknown Artist";
    try {
        byte[] art;
        art = mediaMetadataRetriever.getEmbeddedPicture();
        Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
        imageView.setImageBitmap(songImage);
    }
    catch (Exception e){
        imageView.setBackgroundColor(Color.BLACK);
    }
    Toast.makeText(MainActivity.this,artist,Toast.LENGTH_SHORT).show();

    //Controls
    ctrl.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                ctrl.setText("║");
            }
            else {
                mediaPlayer.pause();
                ctrl.setText("►");
            }
            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            handler.postDelayed(runnable,1);
        }
    });

    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            ctrl.setText("►");
        }
    });

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            handler.removeCallbacks(runnable);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            handler.removeCallbacks(runnable);
            mediaPlayer.seekTo(seekBar.getProgress());
            handler.postDelayed(runnable,1);
        }
    });
}

//update seekBar
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        seekBar.setProgress(mediaPlayer.getCurrentPosition());
        handler.postDelayed(this,1);
    }
};
private String[] getAudioList() {
    final Cursor mCursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA }, null, null,
            "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

    int count = mCursor.getCount();

    String[] songs = new String[count];
    String[] mAudioPath = new String[count];
    int i = 0;
    if (mCursor.moveToFirst()) {
        do {
            songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
            mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            i++;
        } while (mCursor.moveToNext());
    }

    mCursor.close();

    return songs;
}private String[] getmAudioPath() {
    final Cursor mCursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA }, null, null,
            "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

    int count = mCursor.getCount();

    String[] songs = new String[count];
    String[] path = new String[count];
    int i = 0;
    if (mCursor.moveToFirst()) {
        do {
            songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
            path[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            i++;
        } while (mCursor.moveToNext());
    }

    mCursor.close();

    return path;
}
}

2 个答案:

答案 0 :(得分:0)

在您的代码中,每次选择新歌时,您都不会检查媒体播放器是否正在播放。

if(mediaPlayer.isPlaying())
  {mediaplyer.stop()}

你需要停止它然后再重置它。 尝试将activitg标签的Manifest文件中的启动模式设置为singleTask。

<activity
        android:name=".MainActivity"
        android:launchMode="singleTask">

如果您希望自己摆脱这一切,我建议您使用绑定服务。它将帮助您管理媒体播放器状态,并将继续在后台运行。这个伟大的tutorial可能有所帮助。

答案 1 :(得分:0)

如您所知:onCreate()onStart()onResume()将在您启动Activity.So时被调用。为了避免onCreate召回,您可以使用布尔值示例onCreate的{​​{1}}方法设置为false,然后在第一次使用isActivityReopened时设置为true。这是一个你可以从中激发灵感的例子:

onCreate