BroadcastReceiver多次触发

BroadcastReceiver多次触发

本文介绍了android.location.PROVIDERS_CHANGED BroadcastReceiver多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试广播接收器,并在日志中打印GPS的状态,以了解其是否按预期工作,并且我发现了一些奇怪的行为(也许这并不奇怪,但我没有期待它.)

I'm testing out a Broadcast Receiver and printing the state of GPS in my logs to get a feel for if it works as intended, and I found some odd behavior (maybe it isn't odd, but I didn't expect it.)

每当切换GPS时(如果是一段时间以来第一次),BroadcastReceiver都需要一段时间才能接收到该事件,当它触发时,它将触发多次(大约10次).之后,将其切换为开和关时,每次都会触发两次.

Whenever one toggled GPS, if it was the first time in a while, it'll take a while for the BroadcastReceiver to receive the event, and when it does, it fires off many times (around 10). After that, when one toggles it on and off, it gets fired off twice each time.

这是为什么?

这就是我的清单中的内容:

This is what I have in my manifest:

<receiver android:name=".receivers.GpsLocationReceiver" >
    <intent-filter>
        <action android:name="android.location.PROVIDERS_CHANGED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

推荐答案

您可以使用sharedpreference和线程来避免此问题但这不是解决此问题的正确方法

You can avoid this problem using sharedpreference and with an threadbut it is not a proper way to overcome this problem

我的方法如下

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

boolean flage=MainActivity.getpreference();

if(!flage){
    MainActivity.putPreferens(true);
    Log.e("gpssss","gpssss");

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {




                    sleep(2000);

                    MainActivity.putPreferens(false);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();


     }}

}

向主类创建一个sharedpreference并存储布尔值false广泛的演员表

to the main class am create a sharedpreference and store boolean value falsethe the broad cast

这篇关于android.location.PROVIDERS_CHANGED BroadcastReceiver多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:35