258

AndroidOSでアプリを開発しています。位置情報サービスが有効になっているかどうかを確認する方法がわかりません。

有効になっている場合は「true」を返し、有効になっていない場合は「false」を返すメソッドが必要です(したがって、最後の場合は、ダイアログを表示して有効にすることができます)。

4

22 に答える 22

404

以下のコードを使用して、gpsプロバイダーとネットワークプロバイダーが有効になっているかどうかを確認できます。

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 user
    new AlertDialog.Builder(context)
        .setMessage(R.string.gps_network_not_enabled)
        .setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        })
        .setNegativeButton(R.string.Cancel,null)
        .show();    
}

また、マニフェストファイルに、次の権限を追加する必要があります

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
于 2012-04-25T08:18:22.243 に答える
230

私はチェックのためにこのコードを使用します:

public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

        } catch (SettingNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

    }else{
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }


} 
于 2014-04-10T07:00:53.927 に答える
72

2020年の今のように

最新、最良、最短の方法は

@SuppressWarnings("deprecation")
public static Boolean isLocationEnabled(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        // This is a new method provided in API 28
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isLocationEnabled();
    } else {
        // This was deprecated in API 28
        int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                Settings.Secure.LOCATION_MODE_OFF);
        return (mode != Settings.Secure.LOCATION_MODE_OFF);
    }
}
于 2019-02-12T11:11:52.427 に答える
56

AndroidXに移行して使用する

implementation 'androidx.appcompat:appcompat:1.3.0'

LocationManagerCompatを使用します

Javaの場合

private boolean isLocationEnabled(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return LocationManagerCompat.isLocationEnabled(locationManager);
}

Kotlinで

private fun isLocationEnabled(context: Context): Boolean {
    val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return LocationManagerCompat.isLocationEnabled(locationManager)
}
于 2019-09-26T04:03:15.777 に答える
38

このコードを使用して、ユーザーを設定に誘導し、GPSを有効にすることができます。

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        new AlertDialog.Builder(context)
            .setTitle(R.string.gps_not_found_title)  // GPS not found
            .setMessage(R.string.gps_not_found_message) // Want to enable?
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton(R.string.no, null)
            .show();
    }
于 2012-04-25T08:17:34.610 に答える
15

上記の答えに基づいて、API 23では、システム自体をチェックするだけでなく、「危険な」パーミッションチェックを追加する必要があります。

public static boolean isLocationServicesAvailable(Context context) {
    int locationMode = 0;
    String locationProviders;
    boolean isAvailable = false;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF);
    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        isAvailable = !TextUtils.isEmpty(locationProviders);
    }

    boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
    boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);

    return isAvailable && (coarsePermissionCheck || finePermissionCheck);
}
于 2016-04-15T16:15:44.143 に答える
9

はい、以下で確認できますコードは次のとおりです。

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

マニフェストファイルの許可を得て:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
于 2015-03-19T08:31:46.440 に答える
7

プロバイダーが有効になっていない場合、「パッシブ」が返される最良のプロバイダーです。https://stackoverflow.com/a/4519414/621690を参照してください

    public boolean isLocationServiceEnabled() {
        LocationManager lm = (LocationManager)
                this.getSystemService(Context.LOCATION_SERVICE);
        String provider = lm.getBestProvider(new Criteria(), true);
        return (StringUtils.isNotBlank(provider) &&
                !LocationManager.PASSIVE_PROVIDER.equals(provider));
    }
于 2014-02-06T16:28:15.817 に答える
6

このif句は、私の意見では位置情報サービスが利用可能かどうかを簡単にチェックします。

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        //All location services are disabled

}
于 2014-01-09T11:33:45.840 に答える
4

アンドロイドグーグルマップで現在のジオロケーションを取得するには、デバイスのロケーションオプションをオンにする必要があります。ロケーションがオンになっているかどうかを確認するには、メソッドからこのメソッドを呼び出すだけですonCreate()

private void checkGPSStatus() {
    LocationManager locationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    if ( locationManager == null ) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    try {
        gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex){}
    try {
        network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex){}
    if ( !gps_enabled && !network_enabled ){
        AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this);
        dialog.setMessage("GPS not enabled");
        dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //this will navigate user to the device location settings screen
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        AlertDialog alert = dialog.create();
        alert.show();
    }
}
于 2014-11-19T04:23:34.773 に答える
4

私はNETWORK_PROVIDERにそのような方法を使用しますが、 GPSに追加することができます。

LocationManager locationManager;

onCreateに入れました

   isLocationEnabled();
   if(!isLocationEnabled()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.network_not_enabled)
                .setMessage(R.string.open_location_settings)
                .setPositiveButton(R.string.yes,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    } 

そしてチェックの方法

protected boolean isLocationEnabled(){
    String le = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(le);
    if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return false;
    } else {
        return true;
    }
}
于 2015-12-10T11:06:54.067 に答える
4

これは、が有効になっているtrue場合に「」を返す非常に便利なメソッドです。Location services

public static boolean locationServicesEnabled(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps_enabled = false;
        boolean net_enabled = false;

        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG,"Exception gps_enabled");
        }

        try {
            net_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG,"Exception network_enabled");
        }
        return gps_enabled || net_enabled;
}
于 2016-02-09T23:53:15.223 に答える
4

kotlinの場合

 private fun isLocationEnabled(mContext: Context): Boolean {
    val lm = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || lm.isProviderEnabled(
            LocationManager.NETWORK_PROVIDER)
 }

ダイアログ

private fun showLocationIsDisabledAlert() {
    alert("We can't show your position because you generally disabled the location service for your device.") {
        yesButton {
        }
        neutralPressed("Settings") {
            startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
        }
    }.show()
}

このように呼び出す

 if (!isLocationEnabled(this.context)) {
        showLocationIsDisabledAlert()
 }

ヒント:ダイアログには次のインポートが必要です(Android Studioがこれを処理する必要があります)

import org.jetbrains.anko.alert
import org.jetbrains.anko.noButton

マニフェストでは、次の権限が必要です

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
于 2018-06-29T12:14:14.890 に答える
3

私は最初のコードを使用して作成メソッドisLocationEnabledを開始します

 private LocationManager locationManager ;

protected boolean isLocationEnabled(){
        String le = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(le);
        if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            return false;
        } else {
            return true;
        }
    }

そして、私は条件をチェックします。マップを開き、falseを指定します。ACTION_LOCATION_SOURCE_SETTINGS

    if (isLocationEnabled()) {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        locationClient = getFusedLocationProviderClient(this);
        locationClient.getLastLocation()
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // GPS location can be null if GPS is switched off
                        if (location != null) {
                            onLocationChanged(location);

                            Log.e("location", String.valueOf(location.getLongitude()));
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e("MapDemoActivity", e.toString());
                        e.printStackTrace();
                    }
                });


        startLocationUpdates();

    }
    else {
        new AlertDialog.Builder(this)
                .setTitle("Please activate location")
                .setMessage("Click ok to goto settings else exit.")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        System.exit(0);
                    }
                })
                .show();
    }

ここに画像の説明を入力してください

于 2018-02-26T12:08:14.497 に答える
3

Android 8.1以下では、ユーザーはから「バッテリー節約」モードを有効にできます
Settings > Location > Mode > Battery Saving
このモードではWiFi, Bluetooth or mobile data、GPSの代わりにユーザーの位置を特定するためにのみ使用します。

そのため、ネットワークプロバイダーが有効になってlocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)いて、十分でないかどうかを確認する必要があります。

このコードを使用しているandroidx場合は、実行しているSDKのバージョンを確認し、対応するプロバイダーを呼び出します。

public boolean isLocationEnabled(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return manager != null && LocationManagerCompat.isLocationEnabled(manager);
}
于 2020-09-09T02:39:33.650 に答える
2
private boolean isGpsEnabled()
{
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
于 2014-08-13T11:11:35.773 に答える
2

GoogleMaps doasのように、場所の更新をリクエストしてダイアログを一緒に表示することもできます。コードは次のとおりです。

googleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();
googleApiClient.connect();

LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

builder.setAlwaysShow(true); //this is the key ingredient

PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
    @Override
    public void onResult(LocationSettingsResult result) {
        final Status status = result.getStatus();
        final LocationSettingsStates state = result.getLocationSettingsStates();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                // All location settings are satisfied. The client can initialize location
                // requests here.
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                // Location settings are not satisfied. But could be fixed by showing the user
                // a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    status.startResolutionForResult(getActivity(), 1000);
                } catch (IntentSender.SendIntentException ignored) {}
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are not satisfied. However, we have no way to fix the
                // settings so we won't show the dialog.
                break;
            }
        }
    });
}

詳細が必要な場合は、LocationRequestクラスを確認してください。

于 2016-04-04T15:22:38.027 に答える
2

最も簡単な方法で行うことができます

private boolean isLocationEnabled(Context context){
int mode =Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                        Settings.Secure.LOCATION_MODE_OFF);
                final boolean enabled = (mode != android.provider.Settings.Secure.LOCATION_MODE_OFF);
return enabled;
}
于 2018-12-19T06:11:40.043 に答える
2
public class LocationUtil {
private static final String TAG = LocationUtil.class.getSimpleName();

public static LocationManager getLocationManager(final Context context) {
    return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

public static boolean isNetworkProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

public static boolean isGpsProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.GPS_PROVIDER);
}

// Returns true even if the location services are disabled. Do not use this method to detect location services are enabled.
private static boolean isPassiveProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
}

public static boolean isLocationModeOn(final Context context) throws Exception {
    int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
    return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}

public static boolean isLocationEnabled(final Context context) {
    try {
        return isNetworkProviderEnabled(context) || isGpsProviderEnabled(context)  || isLocationModeOn(context);
    } catch (Exception e) {
        Log.e(TAG, "[isLocationEnabled] error:", e);
    }
    return false;
}

public static void gotoLocationSettings(final Activity activity, final int requestCode) {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    activity.startActivityForResult(intent, requestCode);
}

public static String getEnabledProvidersLogMessage(final Context context){
    try{
        return "[getEnabledProvidersLogMessage] isNetworkProviderEnabled:"+isNetworkProviderEnabled(context) +
                ", isGpsProviderEnabled:" + isGpsProviderEnabled(context) +
                ", isLocationModeOn:" + isLocationModeOn(context) +
                ", isPassiveProviderEnabled(ignored):" + isPassiveProviderEnabled(context);
    }catch (Exception e){
        Log.e(TAG, "[getEnabledProvidersLogMessage] error:", e);
        return "provider error";
    }
}

}

isLocationEnabledメソッドを使用して、位置情報サービスが有効になっていることを検出します。

https://github.com/Polidea/RxAndroidBle/issues/327#ページには、ロケーションモードを使用する代わりに、パッシブプロバイダーを使用しない理由の詳細が記載されています。

于 2020-04-17T08:44:39.280 に答える
1

AndroidXを使用している場合は、以下のコードを使用して、位置情報サービスが有効になっているかどうかを確認してください。

fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
于 2019-12-31T18:49:55.033 に答える
0

ネットワークプロバイダーを確認するには、GPSプロバイダーとネットワークプロバイダーの両方の戻り値を確認する場合、isProviderEnabledに渡される文字列をLocationManager.NETWORK_PROVIDERに変更する必要があります。どちらもfalseは、ロケーションサービスがないことを意味します。

于 2012-11-22T16:48:09.893 に答える
0
    LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

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

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

    if(!gps_enabled && !network_enabled) {
        // notify user
        new AlertDialog.Builder(this)
                .setMessage("Please turn on Location to continue")
                .setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }

                }).
                setNegativeButton("Cancel",null)
                .show();
    }
于 2020-01-28T16:39:58.173 に答える