IT story

Android 기기의 GPS가 활성화되어 있는지 확인하는 방법

hot-time 2020. 5. 9. 09:21
반응형

Android 기기의 GPS가 활성화되어 있는지 확인하는 방법


Android Cupcake (1.5) 지원 기기에서 GPS를 확인하고 활성화하려면 어떻게하나요?


가장 좋은 방법은 다음과 같습니다.

 final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

  private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}

Android에서는 기기에서 GPS가 사용 설정되어 있는지 LocationManager를 사용하여 쉽게 확인할 수 있습니다.

다음은 점검 할 간단한 프로그램입니다.

GPS 사용 여부 :-AndroidManifest.xml에 아래 사용자 권한 줄을 추가하여 위치에 액세스하십시오.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

자바 클래스 파일은

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

출력은 다음과 같습니다

enter image description here

enter image description here


예 GPS 설정은 프라이버시 설정이므로 프로그래밍 방식으로 더 이상 변경할 수 없으며 프로그램에서 켜져 있는지 여부를 확인하고 켜져 있지 않은 경우 처리해야합니다. GPS가 꺼져 있음을 사용자에게 알리고 원하는 경우 사용자에게 설정 화면을 표시하기 위해 이와 같은 것을 사용할 수 있습니다.

위치 제공 업체가 있는지 확인

    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider != null){
        Log.v(TAG, " Location providers: "+provider);
        //Start searching for location and update the location text when update available
        startFetchingLocation();
    }else{
        // Notify users and show settings if they want to enable GPS
    }

If the user want to enable GPS you may show the settings screen in this way.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);

And in your onActivityResult you can see if the user has enabled it or not

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_CODE && resultCode == 0){
            String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if(provider != null){
                Log.v(TAG, " Location providers: "+provider);
                //Start searching for location and update the location text when update available. 
// Do whatever you want
                startFetchingLocation();
            }else{
                //Users did not switch on the GPS
            }
        }
    }

Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.


Here are the steps:

Step 1: Create services running in background.

Step 2: You require following permission in Manifest file too:

android.permission.ACCESS_FINE_LOCATION

Step 3: Write code:

 final LocationManager manager = (LocationManager)context.getSystemService    (Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
  Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show(); 
else
  Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();

Step 4: Or simply you can check using:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

Step 5: Run your services continuously to monitor connection.


Yes you can check below is the code:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

GPS will be used if the user has allowed it to be used in its settings.

You can't explicitly switch this on anymore, but you don't have to - it's a privacy setting really, so you don't want to tweak it. If the user is OK with apps getting precise co-ordinates it'll be on. Then the location manager API will use GPS if it can.

If your app really isn't useful without GPS, and it's off, you can open the settings app at the right screen using an intent so the user can enable it.


This piece of code checks GPS status

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

`


This method will use the LocationManager service.

Source Link

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};

In your LocationListener, implement onProviderEnabled and onProviderDisabled event handlers. When you call requestLocationUpdates(...), if GPS is disabled on the phone, onProviderDisabled will be called; if user enables GPS, onProviderEnabled will be called.

참고URL : https://stackoverflow.com/questions/843675/how-do-i-find-out-if-the-gps-of-an-android-device-is-enabled

반응형