我的 Android 应用程序中未显示当前位置

2024-01-09

我已经编写了用于获取 android 项目中当前位置的代码。但它不会自动选择我的位置并在世界某个地方显示标记,尽管我坐在巴基斯坦。

地图活动代码在这里

 package com.example.uber;

    import androidx.annotation.NonNull;
    import androidx.annotation.RequiresApi;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Build;
    import android.os.Bundle;
    import android.util.Log;

    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;

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

    public class MapsActivity2 extends FragmentActivity implements OnMapReadyCallback {

        private GoogleMap mMap;
        private LocationManager locationManager;
        private LocationListener locationListener;

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps2);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

        }
        /**
         * Manipulates the map once available.
         * This callback is triggered when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera. In this case,
         * we just add a marker near Sydney, Australia.
         * If Google Play services is not installed on the device, the user will be prompted to install
         * it inside the SupportMapFragment. This method will only be triggered once the user has
         * installed Google Play services and returned to the app.
         */
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;

            locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.d("Location", location.toString());

                    mMap.clear();
                    // Add a marker in Sydney and move the camera
                    LatLng newLocation = new LatLng(location.getLatitude(),location.getLongitude());
                    //LatLng sydney = new LatLng(-34, 151);
                    mMap.addMarker(new MarkerOptions().position(newLocation).title("Marker in Sydney"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(newLocation));

                    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
       try{
           List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);

           if(addressList != null && addressList.size()>0){
               Log.d("Address",addressList.get(0).toString());
           }else {
               Log.d("Address","Couldn't find Address");
           }
       }catch (IOException e){
           e.printStackTrace();
       }

                }

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

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            };
            if (Build.VERSION.SDK_INT < 23) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    Activity#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for Activity#requestPermissions for more details.
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

                    //   return;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            } else {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // Ask for permission
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

                } else {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                }
            }

        }
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                }
            }
        }
    }

清单权限我已授予以下许可

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

我的实际位置是31.175669, 74.104891

我已经在模拟器的扩展控制中手动设置了我的位置,如图所示。但我想要的是我的代码动态选择我的位置请帮助我具有扩展控制功能的 Android 模拟器映像 https://i.stack.imgur.com/JOyzS.png


我有同样的问题。当您在 AVD 地图中测试您的应用程序时,将显示 google 公司作为您的位置。但如果您的代码正确,当您在设备中测试该应用程序时,您将正确获取当前位置。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我的 Android 应用程序中未显示当前位置 的相关文章

随机推荐