java– 代码只会在抛出NullPointerException时返回0.0,0.0 GPS坐标

java– 代码只会在抛出NullPointerException时返回0.0,0.0 GPS坐标,第1张

概述这是我使用AndroidLocationAPI的第n次尝试,我似乎无法让它正常工作.这个教程看起来最有希望,但我似乎只能得到这个代码返回0.0,0.0的GPS坐标,这不是很有用…似乎有一个线索,getLocation()返回java.lang.NullPointerException错误,但我不知道我应该在哪里开始寻找它.这是错误:

这是我使用Android Location API的第n次尝试,我似乎无法让它正常工作.这个教程看起来最有希望,但我似乎只能得到这个代码返回0.0,0.0的GPS坐标,这不是很有用…

似乎有一个线索,getLocation()返回java.lang.NullPointerException错误,但我不知道我应该在哪里开始寻找它.

这是错误:

 W/System.err: java.lang.NullPointerException W/System.err:     at androID.content.Contextwrapper.checkPermission(Contextwrapper.java:557)

我尝试制作一个新的权限块,粘贴在底部,但它只是给出了同样的错误.

任何人都可以指出我在正确的方向吗?

代码分为两个类文件:MainActivity.java和GPSTracker.java.

GPSTracker.java

    package com.tutorial.androID.location.API;// http://www.androIDhive.xyz/2016/07/androID-gps-location-manager-tutorial.HTML// with some modifications, especially for new permissionsimport androID.Manifest;import androID.app.Activity;import androID.app.AlertDialog;import androID.app.Service;import androID.content.Context;import androID.content.DialogInterface;import androID.content.Intent;import androID.content.pm.PackageManager;import androID.location.Location;import androID.location.LocationListener;import androID.location.LocationManager;import androID.os.Bundle;import androID.os.IBinder;import androID.provIDer.Settings;import androID.support.annotation.Nullable;import androID.support.v4.app.ActivityCompat;import androID.util.Log;public class GPSTracker extends Service implements LocationListener {    private String TAG = "¤¤";    private final Context mContext;    public GPSTracker(Context mContext) {        this.mContext = mContext;        this.getLocation();    }    boolean isGPSEnabled = false;    boolean isNetworkEnabled = false;    boolean canGetLocation = false;    Location location;    double latitude;    double longitude;    private static final long MIN_disTANCE_CHANGE_FOR_UPDATE = 10; // 10 meters    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 30 sec    protected LocationManager locationManager;    public Location getLocation() {        try {            if(locationManager == null) {                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);            }            if(isGPSEnabled != true) {                isGPSEnabled = locationManager.isProvIDerEnabled(LocationManager.GPS_PROVIDER);            }            if(isNetworkEnabled != true) {                isNetworkEnabled = locationManager.isProvIDerEnabled(LocationManager.NETWORK_PROVIDER);            }            if (!isGPSEnabled && !isNetworkEnabled) {                // no provIDer enabled :p                Log.e(TAG, "getLocation() no provIDer :(");            } else {                this.canGetLocation = true;                // get network location                if (isNetworkEnabled) {                    // permission block:                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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.                        // return Todo;                    } else {                        Log.e(TAG, "getLocation() permission DENIED");                    }                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_disTANCE_CHANGE_FOR_UPDATE, this);                    if(locationManager != null) {                        location = locationManager.getLastKNownLocation(LocationManager.NETWORK_PROVIDER);                        if(location != null) {                            latitude = location.getLatitude();                            longitude = location.getLongitude();                        }                    }                }                // get GPS location                if(isGPSEnabled) {                    if(location == null) {                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_disTANCE_CHANGE_FOR_UPDATE, this);                        Log.d(TAG, "getLocation() GPS Enabled");                        if(locationManager != null){                            location = locationManager.getLastKNownLocation(LocationManager.GPS_PROVIDER);                            if(location != null) {                                latitude = location.getLatitude();                                longitude = location.getLongitude();                            }                        }                    }                }            }        } catch (Exception e) {            Log.e(TAG, "getLocation() ERROR...: " + e);            e.printstacktrace();        }        return location;    }    public double getLatitude() {        if(location != null) {            latitude = location.getLatitude();        }        return latitude;    }    public double getLongitude() {        if(location != null) {            longitude = location.getLongitude();        }        return longitude;    }    @Nullable    @OverrIDe    public IBinder onBind(Intent intent) {        return null;    }    @OverrIDe    public voID onLocationChanged(Location location) {    }    @OverrIDe    public voID onStatusChanged(String provIDer, int status, Bundle extras) {    }    @OverrIDe    public voID onProvIDerEnabled(String provIDer) {        // GPS is ON        Log.d(TAG, "GPS is ON");    }    @OverrIDe    public voID onProvIDerDisabled(String provIDer) {        // GPS is OFF        Log.d(TAG, "GPS is OFF");    }    // GPS dialog    public boolean canGetLocation() {        return this.canGetLocation;    }    // don't really need this when testing    public voID showSettingsAlert() {        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);        alertDialog.setTitle(R.string.gps_settings_Title);        alertDialog.setMessage(R.string.gps_settings_msg);        alertDialog.setPositivebutton(R.string.gps_settings_word, new DialogInterface.OnClickListener() {            public voID onClick(DialogInterface dialog, int which) {                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);                mContext.startActivitIEs(new Intent[]{intent}); // hm...            }        });        alertDialog.show();    }    public voID stopUsingGPS() {        if(locationManager != null) {            locationManager.removeUpdates(GPSTracker.this);        }    }}

在GPSTracker.java中重写但仍然没有工作权限阻止:

int permissionCheck = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);if(!(permissionCheck == PackageManager.PERMISSION_GRANTED)) {    if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, Manifest.permission.ACCESS_FINE_LOCATION)) {        // explanation :p        Log.i(TAG, "nope...");    } else {        // request permission        Log.d(TAG, "Requestion new permission");        ActivityCompat.requestPermissions((Activity) mContext, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);    }}

MainActivity.java

package com.tutorial.androID.location.API;import androID.support.v7.app.AppCompatActivity;import androID.os.Bundle;import androID.util.Log;public class MainActivity extends AppCompatActivity {    String TAG = "¤";    GPSTracker gps;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        gps = new GPSTracker(this);        if(gps.canGetLocation()) {            Log.i(TAG, "onCreate() GPS is ON");            Log.i(TAG, "onCreate() " + gps.getLatitude()+ ", " + gps.getLongitude());        } else {            Log.d(TAG, "onCreate() GPS is OFF");        }    }}

解决方法:

This tutorial seems like the most promising

这是非常糟糕的代码.

I can only seem to get this code to return a GPS coordinate of 0.0, 0.0 which isn’t very useful

这是因为如果getLastKNownLocation()恰好返回一个位置,它将只有一个位置.它不太可能这样做.

Rewritten but still not working permissions block in GPSTracker.java:

这里有两个问题:

>您无法从服务请求权限.
>这不是真正的服务.此代码的作者选择创建一个扩展Service的类,而不实际正确地实现或使用该服务.这是导致NullPointerException的原因,因为这不是正确初始化的Context.

Can anyone please point me in the right direction here?

扔掉所有这些.

FWIW,这里是使用LocationManager API的my sample app.

配方很简单:

步骤1:通过在某些Context上调用getSystemService(Context.LOCATION_SERVICE)来获取LocationManager.我碰巧在一个片段中这样做:

  @OverrIDe  public voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setRetainInstance(true);    template=getActivity().getString(R.string.url);    mgr=(LocationManager)getActivity()      .getSystemService(Context.LOCATION_SERVICE);  }

步骤2:调用requestUpdates(),传入实现LocationListener的内容.就我而言,恰好是片段本身:

  @OverrIDe  @SuppressWarnings({"MissingPermission"})  public voID onStart() {    super.onStart();    mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600000,      1000, this);  }

步骤3:在LocationListener的onLocationChanged()中,使用您获得的位置执行某些 *** 作,在我的示例中,执行AsyncTask以获取天气预报:

  @OverrIDe  public voID onLocationChanged(Location location) {    new FetchForecastTask().execute(location);  }

步骤#4:完成后调用removeUpdates():

  @OverrIDe  @SuppressWarnings({"MissingPermission"})  public voID onStop() {    mgr.removeUpdates(this);    super.onStop();  }

就是这样(除了运行时权限之外,我将其抽象为AbstractPermissionsActivity).

如果需要,可以使用getLastKNownLocation()作为优化,但不要依赖它.

总结

以上是内存溢出为你收集整理的java – 代码只会在抛出NullPointerException时返回0.0,0.0 GPS坐标全部内容,希望文章能够帮你解决java – 代码只会在抛出NullPointerException时返回0.0,0.0 GPS坐标所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1104072.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存