จะแสดงกล่องโต้ตอบเปิดใช้งานตำแหน่งเช่น Google Maps ได้อย่างไร


129

ฉันใช้บริการ Google Play เวอร์ชันล่าสุด (7.0) และทำตามขั้นตอนที่ให้ไว้ในคำแนะนำของพวกเขาและฉันเปิดใช้งานกล่องโต้ตอบตำแหน่งดังที่ด้านล่างซึ่งมีปุ่ม "ไม่เคย" แอปของฉันต้องการตำแหน่งที่อยู่ภายใต้บังคับดังนั้นฉันจึงไม่ต้องการแสดงคำว่า "ไม่เคย" ต่อผู้ใช้เพราะเมื่อผู้ใช้คลิก "ไม่เคย" ฉันจะไม่สามารถรับตำแหน่งหรือขอตำแหน่งได้อีกเลย

ในขณะที่ Google Maps มีเพียงปุ่มใช่และไม่ใช่โดยไม่มีปุ่มไม่เคยมีความคิดอย่างไรที่จะบรรลุสิ่งเดียวกัน

รูปภาพแอปของฉัน ป้อนคำอธิบายภาพที่นี่

รูปภาพของ Google Map ป้อนคำอธิบายภาพที่นี่

คำตอบ:


149

LocationSettingsRequest.BuildersetAlwaysShow(boolean show)มีวิธีการ แม้ว่าเอกสารจะระบุว่าขณะนี้ไม่ได้ทำอะไรเลย (อัปเดตเมื่อ 2015-07-05: เอกสารของ Google ที่อัปเดตได้ลบข้อความนี้ออก) การตั้งค่าbuilder.setAlwaysShow(true);จะเปิดใช้งานการทำงานของ Google Maps: ป้อนคำอธิบายภาพที่นี่

นี่คือรหัสที่ทำให้มันใช้งานได้:

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://stackoverflow.com/a/61868985/12478830


1
@ MarianPaździochค่อนข้างแน่ใจว่าคุณไม่จำเป็นต้องทำเนื่องจากโค้ดตัวอย่างของ Google ใน SettingsApi ไม่จำเป็นต้องใช้
— ไค

1
@Kai ใช่รหัสแปรบน Nexus 5 RESOLUTION_REQUIREDใช้ท่อนผมเห็นว่าเมื่อได้ให้บริการสถานที่ตั้งเป็นครั้งแรกออกก็มักจะฮิต จากนั้นเมื่อฉันยอมรับและเปิดใช้งานตำแหน่งมันจะเข้าชมSUCCESSและข้ามonActivityResult()ไปเลย การกดNoหรือย้อนกลับทำให้กล่องโต้ตอบหายไปหนึ่งวินาทีจากนั้นโหลดใหม่และกดRESOLUTION_REQUIREDอีกครั้ง วิธีเดียวที่จะกำจัดกล่องโต้ตอบคือยอมรับหรือปิดและเปิดแอปอีกครั้ง
— pez

2
@pez ทดสอบบน Galaxy S4 ด้วยบริการ Google Play 7.5.74 และใช้งานได้การยกเลิกไม่ทำให้ RESOLUTION_REQUIRED ถูกเรียก คำแนะนำของฉันคืออัปเดตบริการการเล่นและลองอีกครั้ง หากล้มเหลวให้เริ่มคำถาม StackOverflow ใหม่เพื่อดูว่ามีผู้อื่นพบและแก้ไขปัญหานี้หรือไม่
— ไก่

2
@Kai มันใช้งานได้สำหรับฉัน แต่ถ้าผู้ใช้กดหมายเลขจะทำอย่างไรจะแสดงกล่องโต้ตอบอีกครั้งหรือเพิ่มรหัสที่นั่นหากกดไม่ได้ความช่วยเหลือใด ๆ จะได้รับการชื่นชมอย่างมาก
— Gurpreet singh

1
หมายเหตุ: launchModeไม่สามารถตั้งค่ากิจกรรมของคุณเป็นsingleInstanceอย่างอื่นได้จะไม่ได้ผล กล่องโต้ตอบจะไม่ปรากฏขึ้นและonActivityResultจะถูกเรียกโดยอัตโนมัติ อย่ามีandroid:launchMode="singleInstance"สำหรับกิจกรรมของคุณในAndroidManifest. ฉันเรียนรู้วิธีนี้อย่างหนักหลังจากผ่านไป 3 ชั่วโมง
— ᴛʜᴇᴘᴀᴛᴇʟ

55

ฉันต้องการเพิ่มการเปลี่ยนแปลงบางอย่างในคำตอบของ kai สำหรับผู้ที่กำลังมองหาปุ่มจัดการใช่ / ไม่ใช่

ประกาศค่าคงที่นี้ในกิจกรรมของคุณ

protected static final int REQUEST_CHECK_SETTINGS = 0x1;

โทรsettingsrequest()เข้า onStart () ของคุณ

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
ได้รับจากเอกสารอย่างเป็นทางการ: developers.google.com/android/reference/com/google/android/gms/… หากคุณต้องการเพิ่มเฉพาะแผนที่ในการใช้สิ่งนี้คุณต้องเพิ่มไลบรารีเหล่านั้น (โดยไม่ต้องนำเข้าไลบรารีบริการการเล่นทั้งหมด ): compile 'com.google.android.gms: play-services-maps: 9.0.2' compile 'com.google.android.gms: play-services-location: 9.0.2'
— MatPag

วิธีจัดการกับเหตุการณ์การคลิกของกล่องโต้ตอบนี้และฉันต้องไม่แสดงปุ่ม never ในกล่องโต้ตอบ
— M.Yogeshwaran

เอา settingsrequest () line ออกจาก switch case ใน ActivityOnResult .. นั่นคือสิ่งที่คุณถาม ???
— Veer3383

หากฉันคลิกที่ไม่มีปุ่มของกล่องโต้ตอบ แต่กล่องโต้ตอบนั้นยังคงแสดงอย่างต่อเนื่อง .. ฉันได้ลบบรรทัด settingsrequest () ออกจากกรณีสวิตช์ใน ActivityOnResult แล้ว .. แล้วทำไมมันจึงแสดงอย่างต่อเนื่อง?
— Asmi

คุณอาจต้องทำความสะอาดสร้างโครงการ
— Veer3383

25

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

จากนั้นเพิ่ม Listener

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
ตรวจสอบstackoverflow.com/a/53277287 @BadLoser การใช้ SettingsClient
— Ketan Ramani

ชื่อของการอ้างอิงที่จะนำเข้าคืออะไร? ไม่สามารถแก้ไขสัญลักษณ์ Task
— เดนิส

ฉันพบมัน: การใช้งาน 'com.google.android.gms: play-services-task: 16.0.1'
— Denis

@ เดนิสฉันสามารถใช้implementation 'com.google.android.gms:play-services-location:16.0.0'แทนได้
— CoolMind

25

มันทำงานคล้ายกับแผนที่ Google?
รหัสที่มา: https://drive.google.com/open?id=0BzBKpZ4nzNzUOXM2eEhHM3hOZk0

เพิ่ม Dependency ในไฟล์ 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;
                    }
                }
            });
        }
    }

}

เป็นความสุขของฉัน
— Keshav Gera

1
ดู Broadcast Receiver โพสต์มีประโยชน์และถูกใจฉัน stackoverflow.com/questions/15698790/…
— Keshav Gera

โซลูชั่นที่สมบูรณ์แบบ
— Lalit Sharma

ขอบคุณ Lalit Sharma
— Keshav Gera

ช่วยอัพเดทหน่อยได้ไหมลิงค์เสียตอนนี้โพสต์โค้ดใน GitHub แทน
— Manoj Perumarath

7

Ola Cabs ใช้ Settings API ที่เพิ่งเปิดตัวใหม่เพื่อให้สามารถใช้งานฟังก์ชันนี้ได้ ตาม API ใหม่ผู้ใช้ไม่จำเป็นต้องไปที่หน้าการตั้งค่าเพื่อเปิดใช้งานบริการระบุตำแหน่งที่ให้การผสานรวมที่ราบรื่นสำหรับสิ่งเดียวกัน โปรดอ่านรายละเอียดเพิ่มเติมด้านล่าง:

https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi


ดูเหมือนว่าคำตอบ veer3383 โปรดแก้ไขฉันถ้าฉันผิด
— rakesh kashyap

@rakeshkashyap ใช่เหมือนกัน
— MatPag

ฉันต้องการทราบว่าเป็นไปได้หรือไม่ที่จะทำดังต่อไปนี้: * กำหนดระยะหมดเวลาในการรับตำแหน่ง * ตรวจสอบใน API การตั้งค่า GPS หากเปิดใช้งานเซ็นเซอร์ที่จำเป็นทั้งหมดและแสดงข้อความตามนั้น * หากเป็นไปได้จะกำหนดระยะหมดเวลาได้อย่างไร? ฉันไม่พบการตั้งค่าดังกล่าวเมื่อสร้าง API
— rakesh kashyap

สวัสดีฉันมีปัญหากับการโหลดแผนที่ครั้งที่สองหลังจากเปิด GPS จากสถานะปิดโปรดใครก็ได้ช่วยฉันที: stackoverflow.com/questions/44368960/… ขอบคุณ
— Jaimin Modi

3
SettingsAPIเลิกใช้งานแล้วตอนนี้คุณใช้SettingsClient developers.google.com/android/reference/com/google/android/gms/…
— Saik Caskey

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) {

    }
}

4

นอกจากนี้คุณยังสามารถเพิ่ม LocationRequests หลายรายการสำหรับ Builder เพื่อให้ได้กล่องโต้ตอบ "ใช้ 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

0

ใน 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")
            }
        }
    }
}

0

โปรดตรวจสอบวิธีง่ายๆของฉันเพื่อรับตำแหน่งของผู้ใช้ในเบื้องหน้า

  1. กล่องโต้ตอบการตั้งค่า GPS
  2. ตำแหน่งของผู้ใช้พร้อมข้อมูลสด
  3. คลาส LocationUtility คือวงจรชีวิตของกิจกรรมที่รับรู้เพื่อหยุดชั่วคราว / ดำเนินการอัปเดตตำแหน่งต่อ
  4. ตำแหน่งที่มีFusedLocationProviderClientล่าสุด

https://github.com/Maqsood007/UserLocation-Android/blob/master/app/src/main/java/jetpack/skill/userlocation_android/utils/LocationUtility.kt

ป้อนคำอธิบายภาพที่นี่

ป้อนคำอธิบายภาพที่นี่

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.