Android连接蓝牙耳机播放音乐

参考:

Android实现主动连接蓝牙耳机

具体实现:

    private static final String TAG = "BluetoothA2DPTest";
    private BroadcastReceiver mBroadcastReceiver;
    private BluetoothA2dp mBluetoothA2dp;
    private BluetoothAdapter mBluetoothAdapter;
    private String DEVICE_NAME = "KUWO_K1";
    private BluetoothDevice mBluetoothDevice;
    private MediaPlayer mMediaPlayer;

    private void initParameters(){
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            Log.e(TAG,"have no bluetooth adapter.");
            return;
        }

        if(!mBluetoothAdapter.isEnabled()){
            mBluetoothAdapter.enable();
        }else{
            //开始搜索附近蓝牙
            startDiscovery();
            //绑定BluetoothA2DP,获得service
            getBluetoothA2DP();
        }

        //监听广播
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                BluetoothDevice device;
                switch (intent.getAction()) {
                    case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
                        //<editor-fold>
                        switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {
                            case BluetoothA2dp.STATE_CONNECTING:
                                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                Log.i(TAG, "device: " + device.getName() +" connecting");
                                break;
                            case BluetoothA2dp.STATE_CONNECTED:
                                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                Log.i(TAG, "device: " + device.getName() +" connected");
                                //连接成功,开始播放
                                startPlay();
                                break;
                            case BluetoothA2dp.STATE_DISCONNECTING:
                                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                Log.i(TAG, "device: " + device.getName() +" disconnecting");
                                break;
                            case BluetoothA2dp.STATE_DISCONNECTED:
                                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                Log.i(TAG, "device: " + device.getName() +" disconnected");
//                                setResultPASS();
                                break;
                            default:
                                break;
                        }
                        //</editor-fold>
                        break;
                    case BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED:
                        //<editor-fold>
                        int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1);
                        switch (state) {
                            case BluetoothA2dp.STATE_PLAYING:
                                Log.i(TAG, "state: playing.");
                                break;
                            case BluetoothA2dp.STATE_NOT_PLAYING:
                                Log.i(TAG, "state: not playing");
                                break;
                            default:
                                Log.i(TAG, "state: unkown");
                                break;
                        }
                        //</editor-fold>
                        break;
                    case BluetoothDevice.ACTION_FOUND:
                        //<editor-fold>
                        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        int deviceClassType = device.getBluetoothClass().getDeviceClass();
                        //找到指定的蓝牙设备
                        if ((deviceClassType == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET
                                || deviceClassType == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES)
                                && device.getName().equals(DEVICE_NAME)) {
                            Log.i(TAG, "Found device:" + device.getName());
                            mBluetoothDevice = device;
                            //start bond,开始配对
                            createBond();
                        }
                        //</editor-fold>
                        break;
                    case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                        //<editor-fold>
                        int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,BluetoothDevice.BOND_NONE);
                        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        switch (bondState){
                            case BluetoothDevice.BOND_BONDED:  //配对成功
                                Log.i(TAG,"Device:"+device.getName()+" bonded.");
                                mBluetoothAdapter.cancelDiscovery();  //取消搜索
                                connect();  //连接蓝牙设备
                                break;
                            case BluetoothDevice.BOND_BONDING:
                                Log.i(TAG,"Device:"+device.getName()+" bonding.");
                                break;
                            case BluetoothDevice.BOND_NONE:
                                Log.i(TAG,"Device:"+device.getName()+" not bonded.");
                                //不知道是蓝牙耳机的关系还是什么原因,经常配对不成功
                                //配对不成功的话,重新尝试配对
                                createBond();
                                break;
                            default:
                                break;

                        }

                        //</editor-fold>
                        break;
                    case BluetoothAdapter.ACTION_STATE_CHANGED:
                        //<editor-fold>
                        state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                        switch (state) {
                            case BluetoothAdapter.STATE_TURNING_ON:
                               Log.i(TAG, "BluetoothAdapter is turning on.");
                                break;
                            case BluetoothAdapter.STATE_ON:
                                Log.i(TAG, "BluetoothAdapter is on.");
                                //蓝牙已打开,开始搜索并连接service
                                startDiscovery();
                                getBluetoothA2DP();
                                break;
                            case BluetoothAdapter.STATE_TURNING_OFF:
                               Log.i(TAG, "BluetoothAdapter is turning off.");
                                break;
                            case BluetoothAdapter.STATE_OFF:
                               Log.i(TAG, "BluetoothAdapter is off.");
                                break;
                        }
                        //</editor-fold>
                        break;
                    default:
                        break;
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver, filter);
    }

private void startDiscovery(){
       Log.i(TAG,"mBluetoothAdapter startDiscovery.");
        if(mBluetoothAdapter!=null && mBluetoothAdapter.isEnabled() && !mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.startDiscovery();
        }
    }

    private void getBluetoothA2DP(){
        Log.i(TAG,"getBluetoothA2DP");
        if(mBluetoothAdapter == null){
            return;
        }

        if(mBluetoothA2dp != null){
            return;
        }

        mBluetoothAdapter.getProfileProxy(this, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                if(profile == BluetoothProfile.A2DP){
                    //Service连接成功,获得BluetoothA2DP
                    mBluetoothA2dp = (BluetoothA2dp)proxy;
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {

            }
        },BluetoothProfile.A2DP);
    }

    private void createBond() {
        Log.i(TAG, "createBond");
        mBluetoothDevice.createBond();
    }

    //connect和disconnect都是hide方法,普通应用只能通过反射机制来调用该方法
    private void connect(){
        Log.i(TAG,"connect");
        if(mBluetoothA2dp == null){
            return;
        }
        if(mBluetoothDevice == null){
            return;
        }

        try {
            Method connect = mBluetoothA2dp.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
            connect.setAccessible(true);
            connect.invoke(mBluetoothA2dp,mBluetoothDevice);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            Log.e(TAG,"connect exception:"+e);
            e.printStackTrace();
        }
    }

    private void startPlay(){
        Log.i(TAG, "startPlay");
        AudioManager mAudioManager= (AudioManager)getSystemService(AUDIO_SERVICE);
        if(mAudioManager!=null){
            int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,maxVolume,0);
        }

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+ R.raw.speaker_test);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.reset();
        try {
            mMediaPlayer.setDataSource(this,uri);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //播放完成,可以考虑断开连接
                    disconnect();
                }
            });
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.e(TAG, "Playback error.");
                    return false;
                }
            });
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch(IllegalStateException|IOException e) {
            Log.e(TAG, "Exception: prepare or start mediaplayer");
            setResultFAIL();
        }
    }

    //程序退出前,要release播放器
    private void stopPlay(){
        Log.i(TAG,"stopPlay");
        if(mMediaPlayer!=null){
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void disconnect(){
        Log.i(TAG,"disconnect");
        if(mBluetoothA2dp == null){
            return;
        }
        if(mBluetoothDevice == null){
            return;
        }

        try {
            Method disconnect = mBluetoothA2dp.getClass().getDeclaredMethod("disconnect", BluetoothDevice.class);
            disconnect.setAccessible(true);
            disconnect.invoke(mBluetoothA2dp,mBluetoothDevice);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            Log.e(TAG,"connect exception:"+e);
            e.printStackTrace();
        }
    }

    //取消配对
    private void unPairAllDevices(){
        Log.i(TAG,"unPairAllDevices");
        for(BluetoothDevice device:mBluetoothAdapter.getBondedDevices()){
            try {
                Method removeBond = device.getClass().getDeclaredMethod("removeBond");
                removeBond.invoke(device);
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    //注意,在程序退出之前(OnDestroy),需要断开蓝牙相关的Service
    //否则,程序会报异常:service leaks
    private void disableAdapter(){
        Log.i(TAG,"disableAdapter");
        if(mBluetoothAdapter == null){
            return;
        }

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
        }

       //关闭ProfileProxy,也就是断开service连接
        mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP,mBluetoothA2dp);
        if(mBluetoothAdapter.isEnabled()){
            boolean ret = mBluetoothAdapter.disable();
            Log.i(TAG,"disable adapter:"+ret);
        }
    }
时间: 2024-11-05 22:27:34

Android连接蓝牙耳机播放音乐的相关文章

Android使用Service播放音乐

像音乐这种耗时的和适合后台操作的应当放在Service中进行操作,而不是放在Activity,下面就介绍使用Service的音乐播放器 先创建一个MusicService 配置清单中会自动生成 改Service的声明 在MusicService中的Java代码,里面包含了音乐的相关操作 public class MusicService extends Service { private String path = "mnt/sdcard/123.mp3"; private Media

树莓派2model B 通过蓝牙实现A2DP协议连接手机播放音乐

使用树莓派,开启他的A2DP功能,实现用手机蓝牙控制树莓派播放歌曲.主要操作过程参考http://wangye.org/blog/archives/921/以及英文博客http://blog.sina.com.cn/s/blog_89f6a9130101fi07.html 本机机型:树莓派2model B 蓝牙适配器 4.0版本(iphone 和android机均可以用) 2.0 版本 (iphone不能使用,android可以,苹果的就是傲娇) 开机进入图形界面 在开始提解决方法时,重要的是看

Android实现在线播放音乐

原文地址:http://blog.csdn.net/wwj_748/article/details/20933055 在此感谢原作者 效果实现: 下面介绍具体实现过程: 定义一个具有缓冲效果的播放器:Player 我们看到的缓冲效果,是通过设置拖动条SeekBar的二级进度实现的,这就要设置MediaPlayer的缓冲更新的监听了. 具体代码实现: package com.wwj.download.util; import java.io.IOException; import java.uti

Android实例-MediaPlayer播放音乐和视频(XE8+小米2)

结果: 1.播放视频需要手动放入MediaPlayerControl1控件,设置MediaPlayerControl1.MediaPlayer := MediaPlayer1; 2.播放声音文件正常,但播放器视时发现,第一边正常第二边就报错了(哪位大神知道的,请M我哦,先谢谢了). 3.打包时需要打入MP3与MP4文件,路径为"assets\internal\". 实例代码: 1 unit Unit1; 2 3 interface 4 5 uses 6 System.SysUtils,

android 5.0 播放音乐时闹钟响,此时来电话并挂断,闹钟和音乐同时响

请按照如下方法进行修改: frameworks\base\media\java\android\media\MediaFocusControl.java: 1.import packages: import com.android.internal.telephony.ITelephony; import android.os.ServiceManager; 2.增加获取当前Phone Call State的方法getPhoneCallState(): private int getPhoneC

Android开发---MediaPlayer简单音乐播放器

Android开发-MediaPlayer简单音乐播放器 功能介绍 实现一个简单的播放器,类似网易云音乐形式,功能包括: 播放.暂停,停止,退出功能: 后台播放功能: 进度条显示播放进度.拖动进度条改变进度功能: 播放时图片旋转,显示当前播放时间功能: 界面样式 功能实现 1. MediaPlayer的实现 MediaPlayer常用方法介绍 MediaPlayer的实现包括初始化MediaPlayer,MediaPlayer的功能实现,包括播放.暂停.停止.离开等,具体细节如下: MediaP

Android多媒体框架对音乐播放器的支持

下面介绍一下Andriod多媒体框架对开发者提供的支持有哪些. 1. MediaScannerReceiver 这个广播接收者在接收到ACTION_BOOT_COMPLETED.ACTION_MEDIA_MOUNTED或 ACTION_MEDIA_SCANNER_SCAN_FILE 广播时对SD卡中的图片.音乐和视频文件进行了扫描,因为扫描不能影响用户使用,这里启动了一个服务MediaScannerService,扫描的文件类型如下: /* Audio */ addFileType("MP3&q

Android MVC实现一个音乐播放器

MVCPlayer 我尝试在android上使用MVC模式来开发一个音乐播放器.GitHub地址:https://github.com/skyhacker2/MVCPlayer 什么是MVC 来自维基百科 控制器 Controller - 负责转发请求,对请求进行处理. 视图 View - 界面设计人员进行图形界面设计. 模型 Model - 程序员编写程序应有的功能(实现算法等等).数据库专家进行数据管理和数据库设计(可以实现具体的功能). 那么在android上,Activity就是Cont

android 利用 service 实现音乐播放

今天的播放器利用了service,播放音乐在service端,进度条在activity端,因此主要的工作就是activity和service的交互,本文将利用IBinder进行交互,主要是activity可以调用service的函数,可以参考我的这篇博客. 本文关键点:利用利用IBinder实现activity 控制service 实现功能: 1 控制播放进度: activity调用service的函数,对MediaPlayer进行控制.包括启动时的播放和滑动seekbar时,对MediaPla