耳机插拔状态下的音乐播放

耳机插拔广播的监听建立:

private void registerHeadsetPlugReceiver() {
    headsetPlugReceiver = new HeadsetPlugReceiver();
    headsetPlugReceiver.setActivity(this);
    headsetPlugReceiver.setMediaPlayer(mediaPlayer);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action. HEADSET_PLUG");
    registerReceiver(headsetPlugReceiver, intentFilter);
    }

Receiver的自定义:

public class HeadsetPlugReceiver extends BroadcastReceiver {

    @SuppressWarnings("unused")
    private static final String TAG = "HeadsetPlugReceiver";
    private SoundPool soundPool;
    @SuppressWarnings("unused")
    private Activity activity;
    private MediaPlayer mediaPlayer;

    void setActivity(Activity activity){
        this.activity = activity;
        soundPool = new SoundPool(10,AudioManager.STREAM_SYSTEM,5);
        soundPool.load(activity,R.raw.conn_w,1);
        soundPool.load(activity,R.raw.conn_r,2);
    }

    void setMediaPlayer(MediaPlayer mediaPlayer){
        this.mediaPlayer = mediaPlayer;
    }
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.hasExtra("state")) {
            if (intent.getIntExtra("state", 0) == 0) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
                soundPool.play(1,1, 1, 0, 0, 1);
                Toast.makeText(context, "耳机拔离",
                        Toast.LENGTH_LONG).show();

            } else if (intent.getIntExtra("state", 0) == 1) {
                //soundPool.play(2,1, 1, 0, 0, 1);
                Toast.makeText(context, "耳机插入",
                        Toast.LENGTH_LONG).show();
                mediaPlayer.start();
            }
        }
    }
}

SD卡中音乐的查询:

private void findMusicFromSD(String string){
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(
                musicTableForSD, 
                null, 
                musicTitle + " LIKE ?", 
                new String[]{"%" + string + "%"}, 
                null);
    if(cursor.moveToNext()){
        String path = cursor.getString(cursor.getColumnIndex
            (MediaStore.Audio.AudioColumns.DATA));
        String title = cursor.getString(cursor.getColumnIndex
            (MediaStore.Audio.AudioColumns.TITLE));
        Toast.makeText(this, title, Toast.LENGTH_SHORT)
            .show();
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                //mediaPlayer.start();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            Toast.makeText(this, "无搜索结果", Toast.LENGTH_LONG)
            .show();
        }
    }

MainActivity代码:

public class MainActivity extends Activity {
    private HeadsetPlugReceiver headsetPlugReceiver;
    private MediaPlayer mediaPlayer;
    private EditText edtTitle;
    private Button musicAdd;
    private final Uri musicTableForSD = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
    private final String musicTitle = MediaStore.Audio.AudioColumns.TITLE;  

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

        init();

        //找到指定音乐
        findMusicFromSD("");
        //************registerHeadsetPlugReceiver***********
        registerHeadsetPlugReceiver();
    }

    void init(){
        mediaPlayer = new MediaPlayer();
        edtTitle = (EditText)findViewById(R.id.edt_title);
        musicAdd = (Button)findViewById(R.id.btn_add);
        musicAdd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                findMusicFromSD(edtTitle.getText().toString());

            }
        });
    }
    private void registerHeadsetPlugReceiver() {
        headsetPlugReceiver = new HeadsetPlugReceiver();
        headsetPlugReceiver.setActivity(this);
        headsetPlugReceiver.setMediaPlayer(mediaPlayer);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.HEADSET_PLUG");
        registerReceiver(headsetPlugReceiver, intentFilter);
    }

    @SuppressWarnings("deprecation")
    private void findMusicFromSD(String string){

        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(
                musicTableForSD, 
                null, 
                musicTitle + " LIKE ?", 
                new String[]{"%" + string + "%"}, 
                null);

        if(cursor.moveToNext()){
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA));
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
            Toast.makeText(this, title, Toast.LENGTH_SHORT)
            .show();
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                //mediaPlayer.start();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            AudioManager localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  
            if(localAudioManager.isWiredHeadsetOn()){
                mediaPlayer.start();
            }
        }else{
            Toast.makeText(this, "无搜索结果", Toast.LENGTH_LONG)
            .show();
        }
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(headsetPlugReceiver);
        super.onDestroy();
    }
}

即可;

你可能感兴趣的:(android,音乐,耳机)