programing

Android 장치의 GPS가 활성화되었는지 확인하는 방법

codeshow 2023. 8. 10. 21:43
반응형

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

안드로이드에서는 위치 관리자를 사용하여 GPS가 장치에서 활성화되었는지 여부를 쉽게 확인할 수 있습니다.

여기 확인할 수 있는 간단한 프로그램이 있습니다.

GPS 활성화 여부 : - AndroidManifest.xml의 아래 사용자 권한 줄을 액세스 위치에 추가합니다.

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

Java 클래스 파일은 다음과 같아야 합니다.

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
    }

사용자가 GPS를 활성화하려면 다음과 같은 방법으로 설정 화면을 표시할 수 있습니다.

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

또한 onActivityResult에서 사용자가 활성화했는지 여부를 확인할 수 있습니다.

    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
            }
        }
    }

그것이 그것을 하는 한 가지 방법이고 나는 그것이 도움이 되기를 바랍니다.제가 잘못한 게 있으면 알려주세요.

다음은 단계입니다.

1단계: 백그라운드에서 실행 중인 서비스를 만듭니다.

2단계: 매니페스트 파일에서도 다음 권한이 필요합니다.

android.permission.ACCESS_FINE_LOCATION

3단계: 코드 쓰기:

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

4단계: 또는 다음을 사용하여 간단히 확인할 수 있습니다.

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

5단계: 서비스를 지속적으로 실행하여 연결을 모니터링합니다.

예, 아래의 코드를 확인할 수 있습니다.

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

코틀린에서:GPS 활성화 여부를 확인하는 방법

 val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            checkGPSEnable()
        } 

 private fun checkGPSEnable() {
        val dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
                    ->
                    startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
                })
                .setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
                    dialog.cancel()
                })
        val alert = dialogBuilder.create()
        alert.show()
    }

이 메서드는 위치 관리자 서비스를 사용합니다.

소스 링크

//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;
};

여기 제 경우에 적용된 스니펫이 있습니다.

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

`

GPS는 사용자가 설정에서 사용할 수 있도록 허용한 경우 사용됩니다.

더 이상 명시적으로 이것을 켤 수는 없지만, 그렇게 할 필요는 없습니다. 이것은 정말로 개인 정보 보호 설정이기 때문에, 당신은 그것을 조정하고 싶지 않습니다.사용자가 앱이 정확한 좌표를 얻는 데 문제가 없으면 해당 앱이 켜져 있을 것입니다.그러면 위치 관리자 API는 가능하면 GPS를 사용할 것입니다.

GPS가 없으면 앱이 유용하지 않고 꺼져 있으면 사용자가 활성화할 수 있도록 의도를 사용하여 오른쪽 화면에서 설정 앱을 열 수 있습니다.

Kotlin 솔루션:

private fun locationEnabled() : Boolean {
    val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}

당신의LocationListener,시행하다onProviderEnabled그리고.onProviderDisabled이벤트 핸들러.에 전화할 때.requestLocationUpdates(...)GPS가 , GPS를 사용할 수 없습니다.onProviderDisabled됩니다. GPS를 호됩니다입니다. 사용자가 GPS를 활성화하면onProviderEnabled호출됩니다.

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

반응형