簡體   English   中英

如何讓媒體播放器繼續播放相同的音軌,而不在Android中啟動另一個音軌

[英]How to keep the media player keep playing the same sound track and not starting another one in Android

我在主要活動上有一個操作欄圖標,當您單擊它時會播放一個配樂,並且我可以暫停並正確播放它。 當按下操作欄播放圖標時,我將以下代碼稱為:

private void play() {
    if (!mp.isPlaying()) {
        mp.start();//play sound
        play=true;
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer arg0) {
                mp.seekTo(0);
            }
        });
    } else {
        mp.pause();
        play=false;
    }
}

onOptionsItemSelected代碼:

if (id == com.app.myapp.R.id.play) {
    play();
    invalidateOptionsMenu();
}

我有另一個活動帶有“主頁”按鈕動作圖標,單擊該圖標時,它帶我回到主要活動,並且音軌繼續播放,但是當我再次單擊“播放”圖標時,它將播放與我相同的音軌的另一個實例不想做。 我使用以下代碼返回主要活動:

if (id == com.app.myapp.R.id.homebutton) {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish(); // Call once you redirect to another activity
}

我需要什么額外的代碼來執行我想讓我的應用程序執行的操作?

任何幫助將不勝感激。

賈弗

每次從子活動啟動主要活動時,都會創建主要活動。 由於要在onCreate()函數中創建mediaPlayer實例,因此將創建新的媒體播放器實例,從而導致兩次播放。

修改您啟動主要活動的方式,如下所示。

if (id == com.app.twelveimams.R.id.homebutton) {
    Log.e("kiran", "clear top from introu");
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    startActivity(intent);
    finish(); // Call once you redirect to another activity

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM