locationmanager获取纬度和长度

swvgeqrz  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(372)

我正试着从gps上获取经纬度
我找到了以下链接:
如何获取android gps定位
https://www.vogella.com/tutorials/androidlocationapi/article.html
这是我的密码:

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
            Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                System.out.println("Provider " + provider + " has been selected.");
                onLocationChanged(location);
            } else {
                latituteField.setText("Location not available");
                longitudeField.setText("Location not available");
            }
            return;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
            locationManager.requestLocationUpdates(provider, 400, 1, this);
            return;
        }

    }
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }
    @Override
    public void onLocationChanged(Location location) {
        double lat = (double) (location.getLatitude());
        double lng = (double) (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }}

当我运行此应用程序时,应用程序停止
这是错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.locationmanagertutorial, PID: 13737
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.locationmanagertutorial/com.example.locationmanagertutorial.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.IllegalArgumentException: invalid provider: null
        at android.location.LocationManager.checkProvider(LocationManager.java:2098)
        at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1199)
        at com.example.locationmanagertutorial.MainActivity.onCreate(MainActivity.java:47)
        at android.app.Activity.performCreate(Activity.java:7183)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6944) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

如果有可能,我想从全球定位系统没有互联网的纬度和经度。

zbwhf8kr

zbwhf8kr1#

您应该在检查权限后执行与位置相关的查询。最好创建另一种启动位置服务的方法,如

private void startLocationservice(){
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    if(provider == null){
       provider = LocationManager.GPS_PROVIDER;
    }
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}

现在在oncreate中添加以下代码

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    startLocationservice();
    }
 else{
   String [] missingPermissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION }; 
   ActivityCompat.requestPermissions(activity, missingPermissions, PERMISSIONS_REQUEST_CODE)
 }

添加回调活动

public void onRequestPermissionsResult(int requestCode, int[] grantResults){
if (ActivityCompat.checkSelfPermission(this,    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    startLocationservice();
    }
 }

从活动中删除重复代码

euoag5mw

euoag5mw2#

将以下权限放入android清单(对于locationmanager.gps\u提供程序),并像往常一样使用checkselfpermission方法请求权限。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="yourpackage.com">
    ...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    ...

然后您需要请求位置更新,如下所示:

LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener();
try 
{
  if (locationManager != null) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
  }
} catch (Exception e) {
  //logger.error("Can't access GPS_PROVIDER", e);
}

下面是locationlistener类:

private class LocationListener implements android.location.LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            //logger.trace(String.format("Location changed: provider=%1$s, lat = %2$.4f, lon = %3$.4f, time = %4$tF %4$tT", location.getProvider(), location.getLatitude(), location.getLongitude(), new Date(location.getTime())));
        }

        @Override
        public void onProviderDisabled(String provider) {
//            logger.trace(provider + " disabled");
        }

        @Override
        public void onProviderEnabled(String provider) {
//            logger.trace(provider + " enabled");
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
//            logger.trace(provider + " sent changed to " + Integer.toString(status));
        }
    }

相关问题