java - Android Geolocation 在模拟器中工作但不在手机中工作

标签 java android gps android-permissions android-gps

我制作了一个带有地理定位功能的简单应用,它可以在 TextView 中显示用户的当前位置,例如纬度、经度和 Geocoder cityname countryname postal-code 等。

在模拟器中一切正常,但由于某种原因,我的手机无法检索位置。

模拟器运行的是 android 7.1,我的手机运行的是 android 7.0,但这应该不是问题,因为我在制作应用程序时考虑到了 6.0 marshmallow。

这是代码

“主要 Activity ”

package com.example.slimshady.LocationInfoApp;

import android.Manifest;
import android.content.Context;
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.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    LocationManager locationManager;
    LocationListener locationListener;
    Geocoder geocoder;
    TextView latitude, longitude, city, postcode, country;


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

        latitude = (TextView)findViewById(R.id.latitude);
        longitude = (TextView) findViewById(R.id.longitude);
        city = (TextView)findViewById(R.id.city);
        postcode = (TextView)findViewById(R.id.postcode);
        country = (TextView)findViewById(R.id.country);


        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                updateLocationInfo(location);

            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        // asking permission starts here
        if (Build.VERSION.SDK_INT < 23){

            // api level lower than 23 so no need to ask for permission

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

            }
            catch (SecurityException e){

                e.printStackTrace();
            }
        }
        else {

            // api level greater than or equal to 23 checking if has permission if not VVVV this condition
            // means go ask for permission

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
            }
            else{

                // means api level greater than or equal to 23 and already has permission
                // so no need to go out and ask for permission

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locationListener);

                // last known location because we went to this part means we have been here before
                Location lastKnownLocation =  locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (lastKnownLocation != null) {
                    updateLocationInfo(lastKnownLocation);
                }



            }

        }
        // asking permission ends here


    }

    public void updateLocationInfo(Location location) {

        geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

        try {

            List<Address> locationAddress = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(),1);
            if (locationAddress != null && locationAddress.size() > 0) {

                latitude.setText("Latitude: "+String.valueOf(locationAddress.get(0).getLatitude()));
                longitude.setText("Longitude: "+String.valueOf(locationAddress.get(0).getLongitude()));
                city.setText("City: "+String.valueOf(locationAddress.get(0).getLocality()));
                postcode.setText("Post Code: "+String.valueOf(locationAddress.get(0).getPostalCode()));
                country.setText("Country: "+String.valueOf(locationAddress.get(0).getCountryName()));

            }


        }
        catch (Exception e){

        }

    }

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

            startListening();

        }
    }

    public void startListening(){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locationListener);

        }

    }
}

代码简单且基本,一切都应该可以正常工作,但由于某些原因却没有。

我的意思是我的物理设备中的 GPS 接收器可以与谷歌地图一起使用,所以我知道它没有坏。

看到它在模拟器中运行良好 Image of it working in the emulator

但是相同的代码在我的手机上不起作用,我已经添加了所有权限:

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

看到同一个应用在我的物理设备上无法运行,这是我的物理设备的屏幕截图

Screenshot of it not working on mobile

如您所见,该位置已打开,并且在弹出窗口中询问时我已授予权限。 最后但同样重要的是要证明 GPS 接收器在我的物理设备中工作并且没有损坏。

我使用谷歌地图的截图 Screenshot of me using google maps 我用红圈圈出了 GPS, map 可以获取我的 GPS 位置

最佳答案

如果您在物理设备上使用发布的 apk,那么您必须在 Google API 控制台的限制部分为发布的 apk 添加 SHA1。我认为这有帮助。

如果没有,请通过在物理设备上调试应用程序来显示您的 logcat 错误。

关于java - Android Geolocation 在模拟器中工作但不在手机中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52155506/

相关文章:

android - requestLocationUpdates minTime 参数用途

java - SignalR Java 客户端仅支持 1.3

java - base64 到十六进制不一致的结果

java - 监听 TableView 处于焦点时触发的后退键事件

android - ListView 的自定义单元格与 API9 中的父级宽度不匹配

android - 是否可以减少扫描 BLE 设备的时间?

ios - 在ios8.0 App中从GPS获取位置

java - RMI(JDK 1.6): ClassNotFoundException for <server>_Stub in client-app

java - 使用 HttpUrlConnection 访问 servlet 时出现异常

c# - Lat 和 Long 最近的空间位置