Android LocationSettingsRequest对话框以启用GPS-已跳过onActivityResult()

Android LocationSettingsRequest对话框以启用GPS-已跳过onActivityResult(),android,dialog,Android,Dialog,我的应用程序的一部分需要位置服务,因此如果位置当前已关闭,应用程序将提示用户启用它。我是如何做到这一点的:(也可以在堆栈溢出回答中看到) LocationSettingsRequest.Builder=新建LocationSettingsRequest.Builder() .addLocationRequest(MLLocationRequest); builder.setAlwaysShow(true); PendingResult=LocationServices.SettingsApi.c

我的应用程序的一部分需要位置服务,因此如果位置当前已关闭,应用程序将提示用户启用它。我是如何做到这一点的:(也可以在堆栈溢出回答中看到)

LocationSettingsRequest.Builder=新建LocationSettingsRequest.Builder()
.addLocationRequest(MLLocationRequest);
builder.setAlwaysShow(true);
PendingResult=LocationServices.SettingsApi.checkLocationSettings(mgoogleAppClient,builder.build());
result.setResultCallback(新的ResultCallback()
{
@凌驾
公共void onResult(位置设置结果)
{
最终状态状态=result.getStatus();
final LocationSettingsStates=result.getLocationSettingsStates();
开关(status.getStatusCode())
{
案例位置设置StatusCodes.SUCCESS:
//满足所有位置设置。客户端可以初始化位置
//请求在这里。
...
Log.d(“onResult”、“SUCCESS”);
打破
案例位置设置StatusCodes.RESOLUTION_要求:
//不满足位置设置。但可以通过显示用户来修复
//对话。
日志d(“结果”、“需要决议”);
尝试
{
//通过调用startResolutionForResult()显示对话框,
//并在onActivityResult()中检查结果。
status.startResolutionForResult(OuterClass.this,请求位置);
} 
捕获(发送)
{
//忽略错误。
}
打破
案例位置设置StatusCodes.SETTINGS\u CHANGE\u不可用:
//位置设置不满意。但是,我们无法修复此问题
//设置,这样我们就不会显示对话框。
...
Log.d(“onResult”、“UNAVAILABLE”);
打破
}
}
});
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据)
{
//从未调用此日志
Log.d(“onActivityResult()”,Integer.toString(resultCode));
最终位置设置状态=位置设置状态。来自意图(数据);
开关(请求代码)
{
案例请求位置:
开关(结果代码)
{
案例活动。结果\u正常:
{
//已成功完成所有必需的更改
打破
}
案例活动.RESULT\u已取消:
{
//要求用户更改设置,但选择不更改
打破
}
违约:
{      
打破
}
}
打破
}
}
这段代码运行良好,但是总是跳过ActivityResult()。无论用户是否从
对话框
中按
、或
返回
,都不会运行ActivityResult()

我需要Android调用onActivityResult(),这样,如果用户选择不打开位置服务,我可以适当地处理它

Google的开发者页面(以及上面的代码)明确表示应该调用
onActivityResult()
。有人知道为什么要跳过吗

我也不知道这行的目的是什么:

final LocationSettingsStates states=LocationSettingsStates.fromIntent(数据)

谢谢

编辑:我的应用程序结构的基本信息:

  • 此代码包含在
    片段的
    onResume()
    方法中,该片段实现了
    GoogleAppClient.ConnectionCallbacks
    GoogleAppClient.OnConnectionFailedListener
    LocationListener
    以接收位置更新。我们看到了一个例子
  • onLocationChanged()
    中,
    片段将有一个自定义的
    视图
    调用
    invalidate()
    并使用更新的信息重新绘制自身

我发现您对请求代码使用了不同的常量
请求检查设置
请求位置
。它们有相同的值吗?

对于代码:
final LocationSettingsStates states=LocationSettingsStates.fromIntent(intent)
上述代码的目的是在更改设置后获取位置设置(如使用网络、GPS等)的当前状态

另外,在代码中,我认为应该是
locationsetingssstates.fromIntent(数据)因为这里没有
意图,可能只是输入错误。

更新

下面的原始答案是使用Java和现在已弃用的

以下是使用Kotlin和:

在MainActivity中,定义常数:

companion object {
    const val LOCATION_SETTING_REQUEST = 999
}
原始答案:

看起来主要的问题是所有代码都在一个片段中,而且由于
startResolutionForResult()
需要向其中传递一个活动,因此该活动将获得
onActivityResult()
回调

解决这个问题的一种方法是使用所描述的技术,当结果出现时,从活动中手动调用片段的
onActivityResult()
方法

我只是让这个简单的例子起作用

首先是添加片段的活动,它还具有将
onActivityResult()
的结果传递给片段的功能:

public class MainActivity extends AppCompatActivity{

    LocationFragment lFrag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lFrag = LocationFragment.newInstance();
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, lFrag).commit();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LocationFragment.REQUEST_LOCATION){
            lFrag.onActivityResult(requestCode, resultCode, data);
        }
        else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
下面是片段,它包含显示对话框和处理结果的所有功能。在这个简单的例子中,我只是使用
companion object {
    const val LOCATION_SETTING_REQUEST = 999
}
public class MainActivity extends AppCompatActivity{

    LocationFragment lFrag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lFrag = LocationFragment.newInstance();
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, lFrag).commit();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LocationFragment.REQUEST_LOCATION){
            lFrag.onActivityResult(requestCode, resultCode, data);
        }
        else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
public class LocationFragment extends Fragment
        implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {


    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    PendingResult<LocationSettingsResult> result;
    final static int REQUEST_LOCATION = 199;

    public static LocationFragment newInstance() {
        LocationFragment fragment = new LocationFragment();
        return fragment;
    }

    public LocationFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

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

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_location, container, false);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(30 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);

        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(
                                    getActivity(),
                                    REQUEST_LOCATION);
                        } 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
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.d("onActivityResult()", Integer.toString(resultCode));

        //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(getActivity(), "Location enabled by user!", Toast.LENGTH_LONG).show();
                        break;
                    }
                    case Activity.RESULT_CANCELED:
                    {
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(getActivity(), "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
                break;
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

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


    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    PendingResult<LocationSettingsResult> result;
    final static int REQUEST_LOCATION = 199;

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

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

    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(30 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);

        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_LOCATION);
                        } catch (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
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.d("onActivityResult()", Integer.toString(resultCode));

        //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(MainActivity.this, "Location enabled by user!", Toast.LENGTH_LONG).show();
                        break;
                    }
                    case Activity.RESULT_CANCELED:
                    {
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
                break;
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}
    public mainFragment(){

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        buildGoogleApiClient();
        buildLocationSettingsRequest();

        checkLocationSettings();
        mGoogleApiClient.connect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
    try {
        fragment.startIntentSenderForResult(status.getResolution().getIntentSender(), REQUEST_CHECK_SETTINGS, null, 0, 0, 0, null);
    } catch (IntentSender.SendIntentException e) {
        // Ignore the error.
    }
    break;
public class MainActivity extends Activity implements PlaceFragment.SettingsModifyHandler {

    private static final int LOCATION_SETTINGS_RESULT = 1;
    private OnResultCallback placeCallback;

    ...

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOCATION_SETTINGS_RESULT) {
            if (resultCode == Activity.RESULT_OK) {
                placeCallback.resultOk();
            } else {
                placeCallback.resultFail();
            }
        placeCallback = null;
        }
    }

    @Override
    public void handle(IntentSender intentSender, OnResultCallback callback) {
        placeCallback = callback;
        try {
            startIntentSenderForResult(intentSender, LOCATION_SETTINGS_RESULT, null, 0, 0, 0);
        } catch (IntentSender.SendIntentException e) {
            callback.resultFail();
        }
    }
}

public class PlaceFragment extends Fragment {

    private SettingsModifyHandler settingsModifyHandler;

    ...

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (context instanceof SettingsModifyHandler) {
            settingsModifyHandler = (SettingsModifyHandler) context;
        } else {
            throw new RuntimeException("Parent activity must implement PlaceFragment.SettingsModifyHandler interface");
        }
    }

    /* Callback from module, where you implemented status.getStatusCode().LocationSettingsStatusCodes.RESOLUTION_REQUIRED case
    (status is instance of com.google.android.gms.common.api.Status)
    You provide intentSender here through status.getResolution().getIntentSender() */
    @Override
    public void placeLoadError(IntentSender sender) {
        TextView view_text = (TextView) root.findViewById(R.id.text_error);
        TextView view_btn = (TextView) root.findViewById(R.id.btn_reply);

        view_text.setText("Need to change location settings");
        view_btn.setText("Change");
        view_btn.setOnClickListener(v -> {
            settingsModifyHandler.handle(sender, new SettingsModifyHandler.OnResultCallback() {
                @Override
                public void resultOk() {
                    presenter.loadPlace(placeId);
                }

                @Override
                public void resultFail() {
                    ToastUtils.show("You should change location settings!");
                }
            });
        });
    }

    public interface SettingsModifyHandler {
        void handle(IntentSender intentSender, OnResultCallback callback);

        interface OnResultCallback {
            void resultOk();
            void resultFail();
        }
    }
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


package com.keshav.enablelocationwithokcancelbuttoncontrol;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class LocationAddress
{
    private static final String TAG = "LocationAddress";

    public static void getAddressFromLocation(final double latitude, final double longitude,
                                              final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation(
                            latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());
                        result = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (result != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n\nAddress:\n" + result;
                        bundle.putString("address", result);
                        message.setData(bundle);
                    } else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n Unable to get address for this lat-long.";
                        bundle.putString("address", result);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();
    }
}

package com.keshav.enablelocationwithokcancelbuttoncontrol;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener
{

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */

    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */

    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */

    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */

    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */

    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}


package com.keshav.enablelocationwithokcancelbuttoncontrol;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class LocationAddress
{
    private static final String TAG = "LocationAddress";

    public static void getAddressFromLocation(final double latitude, final double longitude,
                                              final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation(
                            latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());
                        result = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (result != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n\nAddress:\n" + result;
                        bundle.putString("address", result);
                        message.setData(bundle);
                    } else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n Unable to get address for this lat-long.";
                        bundle.putString("address", result);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();
    }
}
startIntentSenderForResult(status.getResolution().getIntentSender(), REQUEST_CODE_LOCATION_SETTING, null, 0, 0, 0, null);
private fun enableLocationIfRequired() {
    val builder = LocationSettingsRequest.Builder()
        .addLocationRequest(LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY))
        .setAlwaysShow(true)

    val settingsClient = LocationServices.getSettingsClient(context!!)

    val task = settingsClient!!.checkLocationSettings(builder.build())
    task.addOnCompleteListener {
        try {
            val response = it.getResult(ApiException::class.java)

            //Success
            Log.d(javaClass.simpleName, "Location is enabled")

        } catch (exception: ApiException) {
            Log.d(javaClass.simpleName, "exception thrown: ${exception.statusCode}")
            when (exception.statusCode) {
                LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
                    // Location settings are not satisfied. But could be fixed by showing the
                    // user a dialog.
                    try {
                        // Cast to a resolvable exception.
                        val resolvable = exception as ResolvableApiException
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        Log.d(javaClass.simpleName, "startResolutionForResult called")

                        this.startIntentSenderForResult(
                            resolvable.resolution.intentSender,
                            RC_LOCATION_ENABLE,
                            null, 0, 0, 0, null
                        )

                    } catch (e: IntentSender.SendIntentException) {
                        // Ignore the error.
                        Log.d(javaClass.simpleName, "IntentSender.SendIntentException")
                    } catch (e: ClassCastException) {
                        // Ignore, should be an impossible error.
                        Log.d(javaClass.simpleName, "ClassCastException")
                    }
                }
                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.
                }
            }
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        RC_LOCATION_ENABLE -> {
            if (resultCode == Activity.RESULT_OK) {
                Log.d(javaClass.simpleName, "Location is enabled by user")
            } else {
                Log.d(javaClass.simpleName, "Location enable request is cancelled by user")
            }
            val lm = context!!.getSystemService(LOCATION_SERVICE) as LocationManager
            if (LocationManagerCompat.isLocationEnabled(lm)) {
                Log.d(javaClass.simpleName, "Location is enabled by user")
            } else {
                Log.d(javaClass.simpleName, "Location enable request is cancelled by user")
            }
        }
    }

}
private lateinit var checkLocationSettings: ActivityResultLauncher<IntentSenderRequest>

override fun onCreate(savedInstanceState: Bundle?) {
    checkLocationSettings = 
        registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // GPS is turned on in system settings.
            }
    }
}
.addOnFailureListener(context) { e ->
    when ((e as? ApiException)?.statusCode) {
        LocationSettingsStatusCodes.RESOLUTION_REQUIRED ->
            try {
                // Cast to a resolvable exception.
                val resolvable = e as ResolvableApiException
                // Old API: show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                // New API: call registerForActivityResult::launch
                // and check the result in callback.
                val intentSenderRequest =
                    IntentSenderRequest.Builder(resolvable.resolution).build()
                checkLocationSettings.launch(intentSenderRequest)
            } catch (sie: IntentSender.SendIntentException) {
                Timber.e("GPS: Unable to execute request.")
            } catch (cce: java.lang.ClassCastException) {
                // Ignore, should be an impossible error.
                Timber.e("GPS: Unable to execute request, ClassCastException.")
            }