【问题标题】:LocationListener doesnt listen for gps when it is disabled. Any idea what am i doing wrong?LocationListener 在禁用时不会侦听 gps。知道我在做什么错吗?
【发布时间】:2019-02-06 09:40:06
【问题描述】:

我试图在 gps 被禁用时弹出一个窗口消息,但在我启用或禁用位置侦听器时没有响应。我不明白我在做什么错。任何人都可以帮我解决这个问题吗?提前致谢!

这是我使用 locationlistener 的代码:

public class MapsActivityy extends AppCompatActivity {

    private LocationManager locationManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        //locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Initialize location manager.
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Check if user has granted permissions.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // We do not have permissions.
            return;
        }

        // Check if we did find a location provider.
        if (locationManager == null) {
            // No gps provider was found. Inform user.
            return;
        }
        // Initialize location manager and register location listener.
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                2000,
                10, locationListenerGPS);


        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            openGpsWindow();
        }else{
            updateLocationUI();
        }



    }




    //Location listener that listens for location state changes.
    LocationListener locationListenerGPS = new LocationListener() {
        @Override
        public void onLocationChanged(android.location.Location location) {
            // Called when the location has changed.
                    }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // Called when the provider status changes.
                    }

        @Override
        public void onProviderEnabled(String provider) {
                    }

        @Override
        public void onProviderDisabled(String provider) {
            // Called when the provider is disabled by the user.
            openGpsWindow();
        }
    };

    //Pops up a window in order to open GPS
    public void openGpsWindow() {
        Intent intent = new Intent(this, EnableGpsWindow.class);
        startActivity(intent);
    }
}

我试图在 gps 被禁用时弹出一个窗口消息,但在我启用或禁用位置侦听器时没有响应。我不明白我在做什么错。任何人都可以帮我解决这个问题吗?提前致谢!

【问题讨论】:

    标签: android gps location


    【解决方案1】:

    使用广播接收器获取启用或禁用 gps 的事件,然后使用内部广播接收器在您的应用程序内广播该事件。

    这是您的广播接收器,它将侦听 gps 事件。

    public class LocationStateChangeBroadcastReceiver extends BroadcastReceiver 
    {
    
    public static final String GPS_CHANGE_ACTION = "com.android.broadcast_listeners.LocationChangeReceiver";
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        if (intent.getAction() != null && intent.getAction().equals(context.getString(R.string.location_change_receiver))) {
            if (!isGpsEnabled(context)) {
                sendInternalBroadcast(context, "Gps Disabled");
            }
        }
    }
    
    private void sendInternalBroadcast(Context context, String status) {
        try {
            Intent intent = new Intent();
            intent.putExtra("Gps_state", status);
            intent.setAction(GPS_CHANGE_ACTION);
            context.sendBroadcast(intent);
    
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public static boolean isGpsEnabled(Context context) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    
        return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
    }
    

    创建内部广播接收器类来接收事件。

    class InternalLocationChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
    
    //        this method will be called on gps disabled
    //        call openGpsWindow  here
        }
    }
    

    现在将这段代码复制到您的活动中以注册广播接收器。

     public class MainActivity extends AppCompatActivity {
    
    InternalLocationChangeReceiver internalLocationChangeReceiver = new
            InternalLocationChangeReceiver();
    
    LocationStateChangeBroadcastReceiver locationStateChangeBroadcastReceiver = new LocationStateChangeBroadcastReceiver();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            registerReceiver(locationStateChangeBroadcastReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
    
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(LocationStateChangeBroadcastReceiver.GPS_CHANGE_ACTION);
            registerReceiver(internalLocationChangeReceiver, intentFilter);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(locationStateChangeBroadcastReceiver);
        unregisterReceiver(internalLocationChangeReceiver);
    }
    }
    

    【讨论】:

    • 但我还需要扩展 AppCompatActivity,我该如何使用广播接收器?
    • 对不起,由于格式不正确,您无法在代码块中看到类名。创建一个名为 LocationStateChangeBroadcastReceiver 的新类,该类将扩展 BroadcastReceiver 而不是您的活动。我已经用适当的缩进编辑了答案。
    • 你发给我的是如果 gps 启用对吗?我想禁用 gps 来打开我的功能 openGpsWindow 这是怎么回事?
    • 我明白这一点,但我要在哪里调用我的函数 openGpsWindow ()?
    • 我已经粘贴了活动代码并更新了答案,代码运行良好,重新检查您在 LocationStateChangeBroadcastReceiver 类中的代码。
    【解决方案2】:

    Don't use the gps provider , Kindly use the Fused location services , i have shared a code of using it already and mention the code to check the location request, just tap on link

     var locationRequest = LocationRequest()
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            locationRequest.setInterval(5000)
            locationRequest.setFastestInterval(1000)
            locationRequest.setSmallestDisplacement(2f)
    // Create LocationSettingsRequest object using location request
            val builder = LocationSettingsRequest.Builder()
            builder.addLocationRequest(locationRequest)
            val locationSettingsRequest = builder.build()
    
            // Check whether location settings are satisfied
            // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
            val settingsClient = LocationServices.getSettingsClient(this)
            settingsClient.checkLocationSettings(locationSettingsRequest)
                    .addOnFailureListener {
    
                        AppUtils.showToast(this,getString(R.string.enable_high_accuracy_mode),Toast.LENGTH_LONG).hashCode()
                        val callGPSSettingIntent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                       this@BusDriverDashboardActivity.startActivityForResult(callGPSSettingIntent,1)
                    }.addOnSuccessListener { }
    

    https://stackoverflow.com/a/54551020/4754710

    【讨论】:

    • 你的代码让我很困惑我不太明白,我不是那么熟悉。但是 gps 提供商为什么不工作?
    • Google 将 Providers 升级为 Fused 客户端。
    猜你喜欢
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多