如何在通话期间暂停背景音乐

时间:2015-05-29 14:56:29

标签: android media-player phone-state-listener

public class MainActivity extends Activity implements OnClickListener {
    Button start,stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start=(Button) findViewById(R.id.button1);
        stop=(Button) findViewById(R.id.button2);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);

         TelecomManager tm=(TelecomManager) getSystemService(TELEPHONY_SERVICE);


    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i=new Intent(this,MyService.class);
        if(v.getId()==R.id.button1) {
        startService(i);
        } else if(v.getId()==R.id.button2) {
            stopService(i);
        }
    }
}

MyService.java

public class MyService extends Service {
    MediaPlayer player;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        player=MediaPlayer.create(this, R.raw.song1);
    }

    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        player.start();
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
       if (!(player == null)) {
            if (player.isPlaying()) {
                player.stop();
                player.release();
                player = null;
            }
        }

1 个答案:

答案 0 :(得分:3)

在您的服务中,您可以通过PhoneStateListener

注册TelephonyManager.listen(PhoneStateListener, int)

但由于界面非常大,您也可以在服务中注册一个BroadcastReceiver

 IntentFilter phoneStateFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    registerReceiver(phoneStateReceiver, phoneStateFilter);

在您的BroadcastReceiver中,您可以通过

检查手机状态
String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);