1. 程式人生 > >來電對播放音樂的影響

來電對播放音樂的影響

佈局

<EditText
    android:id="@+id/mediaFileName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="gangstabop.mp3">

    <requestFocus />
</EditText>


<LinearLayout
    android:id="@+id/linearButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/playButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放" />

    <SeekBar
        android:id="@+id/playSeekBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="5dp"
        android:layout_weight="1" />

    <Button
        android:id="@+id/replayButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:text="重播" />
</LinearLayout>

程式碼

package test.com.mp3;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;//媒體播放器
    private Button playButton;
    private Button replayButton;
    private boolean isCellPlay;/*在結束通話電話的時候,用於判斷是否為是來電時中斷*/
    private boolean isSeekBarChanging;//互斥變數,防止進度條與定時器衝突。
    private int currentPosition;//當前音樂播放的進度
    private SeekBar seekBar;
    private Timer timer;
    private static final String TAG = "MediaActivity";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //例項化媒體播放器
        mediaPlayer = new MediaPlayer();

        //監聽滾動條事件
        seekBar = (SeekBar) findViewById(R.id.playSeekBar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());

        // 監聽[播放或暫停]事件
        playButton = (Button) findViewById(R.id.playButton);
        playButton.setOnClickListener(new PalyListener());

        //監聽[重播]事件
        replayButton = (Button) findViewById(R.id.replayButton);
        replayButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mediaPlayer.reset();
                currentPosition = 0;
                play();
            }
        });

        //監聽來電事件
        TelephonyManager phoneyMana = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        phoneyMana.listen(new myPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }

    /*銷燬時釋資源*/
    @Override
    protected void onDestroy() {
        mediaPlayer.release();
        timer.cancel();
        timer = null;
        mediaPlayer = null;
        super.onDestroy();
    }

    /*播放或暫停事件處理*/
    private class PalyListener implements View.OnClickListener {
        public void onClick(View v) {
            if (playButton.getText().toString().equals("暫停")) {
                currentPosition = mediaPlayer.getCurrentPosition();//記錄播放的位置
                mediaPlayer.stop();//暫停狀態
                playButton.setText("播放");
                timer.purge();//移除所有任務;
            } else {
                mediaPlayer.pause();
                play();
            }
        }
    }

    /*播放處理*/
    private void play() {
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//設定音訊型別
            mediaPlayer.setDataSource("http://file.kuyinyun.com/group1/M00/90/B7/rBBGdFPXJNeAM-nhABeMElAM6bY151.mp3");
            mediaPlayer.prepareAsync();//資料緩衝
                /*監聽快取 事件,在緩衝完畢後,開始播放*/
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    playButton.setText("暫停");
                    seekBar.setMax(mediaPlayer.getDuration());
                    if (currentPosition > 0)
                        mp.seekTo(currentPosition);
                }
            });
            //監聽播放時回撥函式
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (!isSeekBarChanging) {
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                }
            }, 0, 50);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "播放錯誤", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            System.out.println(e);
        }
    }

    /*來電事件處理*/
    private class myPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING://來電,應當停止音樂
                    if (mediaPlayer.isPlaying() && playButton.getText().toString().equals("暫停")) {
                        currentPosition = mediaPlayer.getCurrentPosition();//記錄播放的位置
                        mediaPlayer.stop();
                        isCellPlay = true;//標記這是屬於來電時暫停的標記
                        playButton.setText("播放");
                        timer.purge();//移除定時器任務;
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE://無電話狀態
                    if (isCellPlay) {
                        isCellPlay = false;
                        mediaPlayer.reset();
                        play();
                    }
                    break;
            }
        }
    }

    /*進度條處理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // fromUser判斷是使用者改變的滑塊的值
            if (fromUser) {//<span style="color:#ff0000;"> 注意點</span>
                try {
                    if (!mediaPlayer.isPlaying()) {
                        try {
                            mediaPlayer.reset();
                            mediaPlayer.setDataSource("http://file.kuyinyun.com/group1/M00/90/B7/rBBGdFPXJNeAM-nhABeMElAM6bY151.mp3");
                            mediaPlayer.prepareAsync();
                            // mPlayer.prepare();
                            mediaPlayer.start();
                        } catch (IllegalStateException | IOException e) {
                            e.printStackTrace();
                        }
                    }
                    mediaPlayer.seekTo(seekBar.getProgress());
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            }
        }

        /*滾動時,應當暫停後臺定時器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑動結束後,重新設定值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }
}