如何捕捉 GPS 关闭广播一次?

How to catch GPS off broadcast once?

我已经上网了,但我没有找到解决问题的办法。

在我的 android 应用程序中,每次用户关闭 GPS 时,我都必须捕获并向服务器发送通知。这个时候我已经写了这段代码

在 Android 清单中:

    <receiver android:name="proguide.prosegur.scr.BL.receivers.GPSStatusBroadcastReceiver">
        <intent-filter>
            <action android:name="android.location.PROVIDERS_CHANGED" />
        </intent-filter>
    </receiver>

在 GPSStatusBroadcastReceiver class:

public class GPSStatusBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
    if (arg1.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        // here I have to send the notification
    }
}

问题是每次用户放下 GPS 时,我都会使用相同的 Context 和 Intent 参数调用此函数两次(我一次只能发送 1 个通知)。

重要说明:它必须在 API 级别 8 下工作。

那么,为什么这种情况会发生两次?我该怎么做(做对了,不要弄乱代码)一次只发送 1 个通知?谢谢,对不起我的英语。

试试这个:

public class GpsReceiver extends BroadcastReceiver {        
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            final String action = intent.getAction();
            if (action.equals(LocationManager.PROVIDERS_CHANGED_ACTION)) {
                // GPS is switched off.
                if (!context.getSystemService(Context.LOCATION_SERVICE).isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    // Do something.
                }
            } 
        }
    }
}

此外,您应该使用 Android 提供的变量 LocationManager.PROVIDERS_CHANGED_ACTION 而不是硬编码 "android.location.PROVIDERS_CHANGED"

不要在 AndroidManifest.xml 文件中设置 GPS 接收器,而是通过 Service 注册您的 GPS 接收器,如下所示:

public class GpsService extends Service {
    private BroadcastReceiver mGpsReceiver;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       super.onStartCommand(intent, flags, startId);
       registerReceiver();
       return Service.START_NOT_STICKY;
    }
    private void registerReceiver() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
            this.mGpsReceiver = new GpsReceiver();
            this.registerReceiver(this.mGpsReceiver, mIntentFilter);
        }       
    }
}

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

我的方法如下

 @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();


     }}

}

主要 class 我正在创建一个共享首选项并存储布尔值 false 广播将工作一次。