如何像谷歌地图一样显示启用位置对话框?

138
我使用最新版本的Google Play服务(7.0),按照他们的指南进行操作,并启用了如下的位置对话框,其中包含一个“永不”按钮。我的应用程序强制需要位置,因此我不想向用户显示“永不”,因为一旦用户点击“永不”,我将无法再次获取位置或请求位置。
然而,Google地图只有“是”和“否”按钮,没有“永不”按钮,您有什么想法来实现相同的功能吗?
我的应用程序的图片 输入图片描述 谷歌地图的图片 输入图片描述

这是我为Kotlin用户提供的解决方案:https://dev59.com/z10Z5IYBdhLWcg3wpRhW#68359749 - Shoaib Kakal
13个回答

151

LocationSettingsRequest.Builder有一个方法setAlwaysShow(boolean show)。调用builder.setAlwaysShow(true);将启用Google Maps行为,尽管文档指出它目前没有做任何事情(已于2015年7月5日更新:更新的Google文档已删除此措辞): enter image description here

以下是使其工作的代码:

if (googleApiClient == null) {
    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 e) {
                        // Ignore the error.
                    }
                    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;
            }
        }
    });
}

来自Android文档

有关Kotlin,请参见此处: https://dev59.com/XF0a5IYBdhLWcg3w6sZk#61868985


1
@MarianPaździoch,我很确定你不需要这样做,因为Google在SettingsApi上的示例代码并不需要它。 - Kai
2
@Kai 是的,代码在Nexus 5上没有修改。使用日志,我发现当位置服务最初关闭时,它总是会触发RESOLUTION_REQUIRED。然后一旦我接受并启用位置,它就会触发SUCCESS,并完全跳过onActivityResult()。按下“否”或返回键会使对话框消失一秒钟,然后重新加载并再次触发RESOLUTION_REQUIRED。摆脱对话框的唯一方法是接受或关闭并重新打开应用程序。 - pez
2
@pez 在 Galaxy S4 上测试了 Google Play 服务 7.5.74,并且它可以正常工作,取消操作不会导致调用 RESOLUTION_REQUIRED。我的建议是更新 Play 服务并重试。如果仍然失败,请发起一个新的 StackOverflow 问题,看看其他人是否遇到并解决了这个问题。 - Kai
2
@Kai,这对我有用,但如果用户按了“否”,该怎么再次显示对话框或添加一些代码呢?非常感谢您的帮助。 - Gurpreet singh
1
注意:您的活动的“launchMode”不能设置为“singleInstance”,否则这将无法正常工作。对话框将永远不会显示出来,并且“onActivityResult”将自动调用。在“AndroidManifest”中不要将您的活动设置为“android:launchMode =”singleInstance“”。我在经历了3个小时之后才学到了这一点。 - ᴛʜᴇᴘᴀᴛᴇʟ
显示剩余23条评论

55

对于那些想要处理“是/否”按钮的人,我想在Kai的答案上增加一些更改。

在您的活动中声明此常量:

protected static final int REQUEST_CHECK_SETTINGS = 0x1;

在您的 onStart() 中调用 settingsrequest()

public void settingsrequest()
    {
        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(mGoogleApiClient, 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(MainActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        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;
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        startLocationUpdates();
                        break;
                    case Activity.RESULT_CANCELED:
                        settingsrequest();//keep asking if imp or do whatever
                        break;
                }
                break;
        }
    }

1
从官方文档中获取:https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi如果您只需要添加地图,则必须添加这些库(而不导入整个Play服务库): compile 'com.google.android.gms:play-services-maps:9.0.2' compile 'com.google.android.gms:play-services-location:9.0.2' - MatPag
如果我点击对话框的“否”按钮,该对话框仍然会持续出现。我已经从ActivityOnResult的switch case中删除了settingsrequest()行,为什么它仍然会持续显示? - Asmi
Builder被实现为LocationSettingsRequest类的内部类,请参考文档获取更多细节:https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi - Veer3383
你好,我有一个问题,当我打开GPS并尝试第二次加载数据时,地图没有缩放到特定位置。请问有人可以在这里看一下:https://stackoverflow.com/questions/44368960/issue-with-updating-googlemap-by-doing-gps-on-off - Jaimin Modi
我认为你的答案有问题,你没有构建GoogleApiClient。 - Dhruv Tyagi
显示剩余5条评论

28

LocationServices.SettingsApi已经被弃用,现在我们使用SettingsClient

    LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10);
        mLocationRequest.setSmallestDisplacement(10);
        mLocationRequest.setFastestInterval(10);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new 
        LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);

然后检查当前位置设置是否满足要求。 创建 LocationSettingsResponse 任务:

        Task<LocationSettingsResponse> task=LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());

然后添加监听器。
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
            @Override
                    public void onComplete(Task<LocationSettingsResponse> task) {
                        try {
                            LocationSettingsResponse response = task.getResult(ApiException.class);
                            // All location settings are satisfied. The client can initialize location
                            // requests here.

                        } catch (ApiException exception) {
                            switch (exception.getStatusCode()) {
                                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                    // Location settings are not satisfied. But could be fixed by showing the
                                    // user a dialog.
                                    try {
                                        // Cast to a resolvable exception.
                                        ResolvableApiException resolvable = (ResolvableApiException) exception;
                                        // Show the dialog by calling startResolutionForResult(),
                                        // and check the result in onActivityResult().
                                        resolvable.startResolutionForResult(
                                                HomeActivity.this,
                                                101);
                                    } catch (IntentSender.SendIntentException e) {
                                        // Ignore the error.
                                    } catch (ClassCastException e) {
                                        // Ignore, should be an impossible error.
                                    }
                                    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;
                            }
                        }
                    }
                });

已添加 onActivityResult

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case 101:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        Toast.makeText(HomeActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(HomeActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

请参考链接SettingsClient


1
请使用SettingsClient,参见 https://dev59.com/qVwX5IYBdhLWcg3w6S4h#53277287 @BadLoser - Ketan Ramani
导入依赖项的名称是什么?无法解析符号“Task”。 - Greelings
我找到了它:implementation 'com.google.android.gms:play-services-tasks:16.0.1' - Greelings
@Denis,我可以使用implementation 'com.google.android.gms:play-services-location:16.0.0'代替。 - CoolMind

25

它的工作方式类似于谷歌地图吗?
源代码:https://drive.google.com/open?id=0BzBKpZ4nzNzUOXM2eEhHM3hOZk0

在 build.gradle 文件中添加依赖项:

compile 'com.google.android.gms:play-services:8.3.0'

或者

compile 'com.google.android.gms:play-services-location:10.0.1'

输入图像描述

public class LocationOnOff_Similar_To_Google_Maps extends AppCompatActivity {

    protected static final String TAG = "LocationOnOff";


    private GoogleApiClient googleApiClient;
    final static int REQUEST_LOCATION = 199;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setFinishOnTouchOutside(true);

        // Todo Location Already on  ... start
        final LocationManager manager = (LocationManager) LocationOnOff_Similar_To_Google_Maps.this.getSystemService(Context.LOCATION_SERVICE);
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) {
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
            finish();
        }
        // Todo Location Already on  ... end

        if(!hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)){
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not Supported",Toast.LENGTH_SHORT).show();
        }

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) {
            Log.e("keshav","Gps already enabled");
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not enabled",Toast.LENGTH_SHORT).show();
            enableLoc();
        }else{
            Log.e("keshav","Gps already enabled");
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
        }
    }


    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null)
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    private void enableLoc() {

        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(LocationOnOff_Similar_To_Google_Maps.this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {

                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            googleApiClient.connect();
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {

                            Log.d("Location error","Location error " + connectionResult.getErrorCode());
                        }
                    }).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);

            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();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(LocationOnOff_Similar_To_Google_Maps.this, REQUEST_LOCATION);

                                finish();
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }
    }

}

1
查看广播接收器帖子,非常有用,像我一样 https://dev59.com/U2Uo5IYBdhLWcg3w3yqi#44881551 - Keshav Gera
1
请问您能否更新链接,由于现在已经失效了,是否可以将代码发布到GitHub上呢? - Manoj Perumarath

7

依赖

compile 'com.google.android.gms:play-services-location:10.0.1'

代码

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public static final int REQUEST_LOCATION=001;

    GoogleApiClient googleApiClient;

    LocationManager locationManager;
    LocationRequest locationRequest;
    LocationSettingsRequest.Builder locationSettingsRequest;
    Context context;


    PendingResult<LocationSettingsResult> pendingResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "Gps is Enabled", Toast.LENGTH_SHORT).show();

        } else {
            mEnableGps();
        }

    }

    public void mEnableGps() {
        googleApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        googleApiClient.connect();
        mLocationSetting();
    }

    public void mLocationSetting() {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(1 * 1000);
        locationRequest.setFastestInterval(1 * 1000);

        locationSettingsRequest = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

        mResult();

    }

    public void mResult() {
        pendingResult = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, locationSettingsRequest.build());
        pendingResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                Status status = locationSettingsResult.getStatus();


                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                        try {

                            status.startResolutionForResult(MainActivity.this, REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException e) {

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

        });
    }


    //callback method
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        Toast.makeText(context, "Gps enabled", Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(context, "Gps Canceled", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

6

GoogleApiClient已被弃用。Kotlin中的新实现方法如下。

依赖项

// Google Maps Location Services
implementation 'com.google.android.gms:play-services-location:17.1.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'

代码

val locationRequest = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(30 * 1000)
    .setFastestInterval(5 * 1000)

val builder = LocationSettingsRequest.Builder()
    .addLocationRequest(locationRequest)
    .setAlwaysShow(true)

val pendingResult = LocationServices
    .getSettingsClient(activity)
    .checkLocationSettings(builder.build())

pendingResult.addOnCompleteListener { task ->
    if (task.isSuccessful.not()) {
        task.exception?.let {
            if (it is ApiException && it.statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                (it as ResolvableApiException).startResolutionForResult(activity,
                    MainActivity.REQUEST_CODE_LOCATION)
            }
        }
    }
}

这个答案也可以进行检查:https://dev59.com/z10Z5IYBdhLWcg3wpRhW#31816683 - Ercan
1
还是个好答案,只需要改动一些代码。 - Nguyễn Minh Khoa

4
您也可以为构建器添加多个LocationRequests,以实现“使用GPS、Wi-Fi和移动网络进行位置服务”对话框,而不仅仅是“使用GPS定位”。
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(createLocationRequest(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY))
                .addLocationRequest(createLocationRequest(LocationRequest.PRIORITY_HIGH_ACCURACY))
                .setAlwaysShow(true);

PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

在我的情况下,只需使用PRIORITY_HIGH_ACCURACY就足以获得句子“使用GPS、Wi-Fi和移动网络进行定位”。但奇怪的是,在真实设备上它可以工作,但在模拟器中却不行。在模拟器中,句子总是没有“使用GPS”开头,尽管我看到模拟器设备有GPS。 - mikep

3

这是我的 Kotlin 示例 -

  private fun enableLocation() {
    val locationRequest = LocationRequest.create()
    locationRequest.apply {
        priority =LocationRequest.PRIORITY_HIGH_ACCURACY
        interval = 30 * 1000.toLong()
        fastestInterval = 5 * 1000.toLong()
    }
    val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)
    builder.setAlwaysShow(true)
    val result=
            LocationServices.getSettingsClient(requireContext()).checkLocationSettings(builder.build())
    result.addOnCompleteListener {
        try {
            val response: LocationSettingsResponse = it.getResult(ApiException::class.java)
            println("location>>>>>>> ${response.locationSettingsStates.isGpsPresent}")
            if(response.locationSettingsStates.isGpsPresent)
                //do something
        }catch (e: ApiException){
            when (e.statusCode) {
                LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
                    val intentSenderRequest =
                        IntentSenderRequest.Builder(e.status.resolution).build()
                    launcher.launch(intentSenderRequest)
                } catch (e: IntentSender.SendIntentException) {
                }
            }
        }
    }
}

使用以下的 getResult 方法

 private var launcher=  registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()){ result->
  if (result.resultCode == Activity.RESULT_OK) {
      Log.d(TAG, "OK")
      
  } else {
      Log.d(TAG, "CANCEL")
      requireContext().toast("Please Accept Location enable for use this App.")
  }
}

代码正在使用最新的代码运行..!! - Najib.Nj

3
在Kotlin中,使用以下代码:
import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.common.api.PendingResult
import com.google.android.gms.common.api.Status
import com.google.android.gms.location.*

class MainActivity : AppCompatActivity() {
    private var googleApiClient: GoogleApiClient? = null
    private val REQUESTLOCATION = 199
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableLoc()
    }
    private fun enableLoc() {
        googleApiClient = GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks {
                override fun onConnected(bundle: Bundle?) {}
                override fun onConnectionSuspended(i: Int) {
                    googleApiClient?.connect()
                }
            })
            .addOnConnectionFailedListener {
            }.build()
        googleApiClient?.connect()
        val locationRequest = LocationRequest.create()
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        locationRequest.interval = 30 * 1000.toLong()
        locationRequest.fastestInterval = 5 * 1000.toLong()
        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)
        builder.setAlwaysShow(true)
        val result: PendingResult<LocationSettingsResult> =
            LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build())
        result.setResultCallback { result ->
            val status: Status = result.status
            when (status.statusCode) {
                LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
                    status.startResolutionForResult(
                        this@MainActivity,
                        REQUESTLOCATION
                    )
                } catch (e: IntentSender.SendIntentException) {
                }
            }
        }
    }
    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUESTLOCATION -> when (resultCode) {
                Activity.RESULT_OK -> Log.d("abc","OK")
                Activity.RESULT_CANCELED -> Log.d("abc","CANCEL")
            }
        }
    }
}

GoogleApiClient已被弃用。应该使用什么? - Shoaib Kakal

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接