如何在Android中获取GPS开关事件?

时间:2018-09-20 12:49:07

标签: android google-location-services

我有一个简单的广播接收器,可以接收GPS的打开/关闭。 当我打开GPS并收到Android框架提供的Improve accuracy dialog?(开始出现在android 8.0中)时,我两次收到android.location.PROVIDERS_CHANGED接收器。

下面是我的示例接收器。

public class LocationServicesChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG,"Intent action is "+intent.getExtras());

}

我已在清单中声明如下

<receiver
      android:name=".geofence.core.LocationServicesChangedReceiver"
      android:exported="false">
      <intent-filter>
           <action android:name="android.location.PROVIDERS_CHANGED" />
       </intent-filter>
</receiver>

问题:

  • 有什么办法可以停止接收多个onReceive()
  • 是否还有其他意图使GPS开启/关闭事件。

1 个答案:

答案 0 :(得分:-1)

有什么办法可以停止接收多个onReceive()?

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().matches("android.location.PROVIDERS_CHANGED"))
    {
        Log.i(TAG, "Location Providers changed");

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //You receive multiple data from more than one Provider, 
        // choose which one you want to use (GPS or NETWORK Provier).

        if (isGpsEnabled) {
            Log.i(TAG, "Location Providers is GPS");
            // put your code in here to get data from GPS PROVIDER.
        }
        else if (isNetworkEnabled) {
            Log.i(TAG, "Location Providers is Network");
            // put your code in here to get data from NETWORK PROVIDER.
        }

    }
}