How do I check if a location-based service is available?

Asked 2 years ago, Updated 2 years ago, 108 views

I'm developing an Android app. I don't know how to check if the GPS is working or not. I need a method to know if it works as true or false right now, so what is there? I'm trying to float a dialog that makes the gps service available when it's false.

android location service

2022-09-22 21:31

1 Answers

If you do like the code below, you can check whether location-based services and networks are currently available or not.

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} } catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} } catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // Notify the user.
    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
    dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // // TODO Auto-generated method stub
                Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(myIntent);
                //get gps
            }
        });
    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // // TODO Auto-generated method stub

            }
        });
    dialog.show();      
}


2022-09-22 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.