How do I find out if the GPS of an Android device is enabled

后端 未结 10 1567
暖寄归人
暖寄归人 2020-11-22 08:36

On an Android Cupcake (1.5) enabled device, how do I check and activate the GPS?

10条回答
  •  旧时难觅i
    2020-11-22 08:54

    In android, we can easily check whether GPS is enabled in device or not using LocationManager.

    Here is a simple program to Check.

    GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location

    
    

    Your java class file should be

    public class ExampleApp extends Activity {
        /** Called when the activity is first created. */
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
            }else{
                showGPSDisabledAlertToUser();
            }
        }
    
        private void showGPSDisabledAlertToUser(){
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Goto Settings Page To Enable GPS",
                    new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    Intent callGPSSettingIntent = new Intent(
                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(callGPSSettingIntent);
                }
            });
            alertDialogBuilder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    dialog.cancel();
                }
            });
            AlertDialog alert = alertDialogBuilder.create();
            alert.show();
        }
    }
    

    The output will looks like

    enter image description here

    enter image description here

提交回复
热议问题