解决Wifi,耳机 等广播接收两次现象

               最近在写一个项目,遇到了断开连接网络时,广播接收两次现象,根据广播接收特性很好解决这个问题,我们可以在 contentReceiver 中定义一个标记变量, 当每次调用此方法的时候,执行++方法,再通过接口回调的方式,利用系统收到广播后自动回调 onReceiver() 方法,实现分辨出两次广播实现代码如下:
public class MusicReceiver extends BroadcastReceiver {

    int mark = 1;
    public   static  final String HEADSET = "true";
    public   static  final String ACTION = "startMusic";
    public   StartMusic  start;

    public MusicReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        mark++;

        Toast.makeText(context, "广播收到", Toast.LENGTH_LONG).show();

        /**
         *     when headset call  startPlaying music
         *     send  a boradcast
         */
        //Intent intent1 = new Intent(ACTION);
       // context.sendBroadcast(intent1);

        if (start!=null) {
            //  descation headset state
            start.againg(mark);


        }

    }

    // callback method
    public interface StartMusic{
        void againg(int text);
    }

    public  MusicReceiver(StartMusic start) {
        this.start = start;
    }
}

MainActivity 方法中:

  public void registtBroadcast(){

        Log.d("mmm", "registtBroadcast: ---------------->注册广播成功");

        Toast.makeText(this, "注册成功--", Toast.LENGTH_LONG).show();
        IntentFilter filter = new IntentFilter();
        MusicReceiver  mr = new MusicReceiver(this);
        filter.addAction(Intent.ACTION_HEADSET_PLUG);
       // registerReceiver(mr,filter,null,handler);
        registerReceiver(mr,filter);
        Log.d(TAG, "registtBroadcast: ---------------->注册广播成功");
        Toast.makeText(this, "注册成功", Toast.LENGTH_LONG).show();

    }

    /**
     * broadcast receive
     * @param text
     */
    @Override
    public void againg(int text) {

        // when music is stop and soft is open

        //headset in
        int position = service.getPosition();
        if (text%3==0) {
            if (!service.isPlay()) {
                //you should get the list position to listner
                service.playOrPause(position);
            }
        }else{
            //headset out
            if (service.isPlay()) {
                service.playOrPause(position);
            }

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值