Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法获取纬度和经度_Java_Android_Location - Fatal编程技术网

Java 无法获取纬度和经度

Java 无法获取纬度和经度,java,android,location,Java,Android,Location,我正试图获取位置信息。我需要经纬度 我正在用我的手机运行和调试。它是4.4.2 我的AndroidManifest文件: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.peylx.brstpcu.voteapp"> <uses-permission andr

我正试图获取位置信息。我需要经纬度

我正在用我的手机运行和调试。它是4.4.2

我的AndroidManifest文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.peylx.brstpcu.voteapp">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".HomeActivity"
            android:label="@string/title_activity_home"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>

</manifest>
当我试着调试我的程序时,它不会运行
onLocationChanged()
方法。所以我无法得到
吐司
消息

如何解决这个问题?

试试这个-

1) 在HomeActivity中实现OnMyLocationChangeListener

2) 抄送福勒。方法-

private Location getMyLocation() {
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);


        // if Location wasn't found
        if (myLocation == null) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);

            String provider = lm.getBestProvider(criteria, true);
            // Use the provider to get the last known location
            myLocation = lm.getLastKnownLocation(provider);
            double lat1 = myLocation.getLatitude();
            double lng1 = myLocation.getLongitude();
            Toast.makeText(HomeActivity.this,"Latitude = " + lat1 + "Longitude = " + lng1,Toast.LENGTH_LONG).show();
        }

        return myLocation;
    }
3) 在onCreate()中调用getMyLocation()方法

它对我有用:)

注意:OnMyLocationChangeListener已被弃用(请查看谷歌文档)

请尝试以下代码:

从OnCreate()方法调用checkLocation()方法:

//********************************************************************************
公共作废检查位置(活动){
locationManager=(locationManager)activity.getSystemService(Context.LOCATION\u服务);
标准c=新标准();
provider=locationManager.getBestProvider(c,false);
位置=获取位置(活动);
List providers=locationManager.getProviders(true);
for(字符串提供程序:提供程序){
Location l=locationManager.getLastKnownLocation(提供者);
Log.d(“位置提供程序”,“位置提供程序:”+l+“位置管理器”+locationManager);
if(l==null){
继续;
}否则{
位置=l;
打破
}
}
locationManager.requestLocationUpdates(提供者,400,1,this);
locationManager.RemoveUpdate(此);
如果(位置!=null){
//获取位置的纬度和经度
onLocationChanged(位置);
//在文本视图上显示
}否则{
//烤面包机。展示烤面包(这个,
//getResources().getString(R.string.NoConnection));
日志d(“卡恩格拉格”,“纬度:+Lat+“lng”+lng+“位置”+位置);
}
}
//================================================================GetLatLang============================
公共位置getLocation(活动){
试一试{
locationManager=(locationManager)activity.getSystemService(Context.LOCATION\u服务);
//获取GPS状态
isGPSEnabled=locationManager.isProviderEnabled(locationManager.GPS\U提供程序);
//获取网络状态
isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK\u提供程序);
如果(!isGPSEnabled&!isNetworkEnabled){
//未启用任何网络提供程序
}否则{
if(可联网){
locationManager.RequestLocationUpdate(locationManager.NETWORK_提供程序,400,0,此);
Log.d(“网络”、“网络启用”);
如果(locationManager!=null){
location=locationManager.getLastKnownLocation(locationManager.NETWORK\u提供程序);
如果(位置!=null){
lat=位置。getLatitude();
lng=location.getLongitude();
}
}
}
//如果启用GPS,则使用GPS服务获取横向/纵向
如果(isGPSEnabled){
if(位置==null){
locationManager.RequestLocationUpdate(locationManager.GPS_提供程序,400,0,此);
Log.d(“GPS”、“GPS启用”);
如果(locationManager!=null){
location=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序);
如果(位置!=null){
lat=位置。getLatitude();
lng=location.getLongitude();
}
}
}
}
}
}捕获(例外e){
e、 printStackTrace();
}
返回位置;
}
@凌驾
已更改位置上的公共无效(位置){
lat=位置。getLatitude();
lng=location.getLongitude();
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
}

首先,您的活动应该实现LocationListener

public class HomeActivity extends AppCompatActivity implements LocationListener{


private LocationManager locationManager;
private LocationListener locationListener;
private double latitude;
private double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Toast.makeText(getApplicationContext(),"Latitude = " + Double.toString(latitude) + "Longitude = " + Double.toString(longitude),Toast.LENGTH_LONG).show();
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
        }
    };
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
            }, 10);

            return;
        }
    } else {
        configureButton();
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 10:
            if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                configureButton();
            return;
    }

}

private void configureButton(){
            locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);

    }
}

你把你的听众放在哪里?我想在活动开始时得到所有这些。所以这就是为什么我在onCreate Section中添加了configureButton()方法,您要求的是button listener,对吗?如果您询问locationListener,我已经在configureButton方法中使用了它,那么您正在实例化一个侦听器,但您没有使用它,那么为什么您认为应该接收位置更新?查看
LocationManager.requestLocationUpdates
方法我尝试使用按钮tooAm我应该添加一些依赖项以使用此方法?我无法在MyLocationListener上实现。LocationListener呢?抱歉,我是新手,如果您正在使用Android Studio,请将依赖项添加为-compile'com.google.Android.gms:play services:*.*.*其中,*表示库的最新版本。然后在活动中实现OnMyLocationChangeListener。根据ua的选择,您可以同时使用LocationListener接口或OnMyLocationChangeListener接口。请参考-谷歌游戏服务。非常感谢!我的代码现在已经在运行了,但我要试试这个too04-18 16:38:04.460 1610-1610/com.peylx.brstpcu.voteapp D/cahngeLag:Lat:0.0lng0.0locationnull 04-18 16:38:04.550 1610-1610/com.peylx.brstpcu.voteapp I/ActivityManager:Timeline:Activity\u idle id:android.os。BinderProxy@41a0ff68时间:15943727204-1816:38:10.3101610-1610/com.peylx.brstpcu.voteapp D/Netw
// ********************************************************************************
    public void checkLocation(Activity activity) {
        locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
        Criteria c = new Criteria();
        provider = locationManager.getBestProvider(c, false);

        location = getLocation(activity);
        List<String> providers = locationManager.getProviders(true);

    for (String provider : providers) {
        Location l = locationManager.getLastKnownLocation(provider);
        Log.d("Location provider", "Location provider : " + l + "locationManager" + locationManager);
        if (l == null) {

            continue;
        } else {
            location = l;
            break;

        }

    }
        locationManager.requestLocationUpdates(provider, 400, 1, this);
        locationManager.removeUpdates(this);

        if (location != null) {
            // get latitude and longitude of the location
            onLocationChanged(location);
            // display on text view

        } else {
            // Toaster.showToast(this,
            // getResources().getString(R.string.NoConnection));
            Log.d("cahngeLag", "Lat: " + lat + "lng" + lng + "location" + location);
        }
    }

    // ===============================GetLatLang============================
    public Location getLocation(Activity activity) {
        try {
            locationManager = (LocationManager) activity.getSystemService(Context.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 {
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 0, this);
                    Log.d("Network", "Network Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            lat = location.getLatitude();
                            lng = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 0, this);
                        Log.d("GPS", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                lat = location.getLatitude();
                                lng = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }

    @Override
    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lng = location.getLongitude();
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
public class HomeActivity extends AppCompatActivity implements LocationListener{


private LocationManager locationManager;
private LocationListener locationListener;
private double latitude;
private double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Toast.makeText(getApplicationContext(),"Latitude = " + Double.toString(latitude) + "Longitude = " + Double.toString(longitude),Toast.LENGTH_LONG).show();
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
        }
    };
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
            }, 10);

            return;
        }
    } else {
        configureButton();
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 10:
            if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                configureButton();
            return;
    }

}

private void configureButton(){
            locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);

    }
}