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

来源:互联网 发布:恒大社会招聘网络面试 编辑:程序博客网 时间:2024/05/29 15:29
               最近在写一个项目,遇到了断开连接网络时,广播接收两次现象,根据广播接收特性很好解决这个问题,我们可以在 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);            }        }
1 0
原创粉丝点击