获取位置Android上的NullPointerException

获取位置Android上的NullPointerException,android,location,Android,Location,这就是我在android应用程序中获取位置的方式。但每次我启动应用程序时,它都会给我NullPointerException,尽管我检查了位置是否为null。这里发生了什么?请帮帮我 public Location getLocation () { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE

这就是我在android应用程序中获取位置的方式。但每次我启动应用程序时,它都会给我NullPointerException,尽管我检查了位置是否为null。这里发生了什么?请帮帮我

public Location getLocation () {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(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 {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    //updates will be send according to these arguments
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();


                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }
这个方法运行在一个服务中,我通过一个意图调用该服务。我使用AsyncTask将我的位置发送到服务器,如下所示:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        Log.i(LOG, "Service started");
        Log.i("asd", "This is sparta");



      new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude());
return START_STICKY;
    }
这是我的日志:

3-04 12:55:03.748    3235-3235/sourcemate.com.locationsender E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: sourcemate.com.locationsender, PID: 3235
    java.lang.RuntimeException: Unable to start service sourcemate.com.locationsender.LocationService@2f790e5a with Intent { cmp=sourcemate.com.locationsender/.LocationService }: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2914)
            at android.app.ActivityThread.access$2100(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1401)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
            at sourcemate.com.locationsender.LocationService.onStartCommand(LocationService.java:75)
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2897)
            at android.app.ActivityThread.access$2100(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1401)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)

请使用该类进行定位

import android.Manifest;
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.util.Log;


public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    public boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    //flag for WIFi
    boolean isWifiEnabled = false;


    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//  private static final long MIN_TIME_BW_UPDATES = 1000 ; // 1 sec

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            isWifiEnabled = locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);


            if (!isGPSEnabled && !isNetworkEnabled && !isWifiEnabled) {
                // no network provider is enabled
            } else {

                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {


                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();

                            }
                        }
                    }
                }


                if (isWifiEnabled) {

                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.PASSIVE_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();

                            }
                        }
                    }

                }
                if (String.valueOf(latitude).equalsIgnoreCase("0.0") || String.valueOf(longitude).equalsIgnoreCase("0.0")) {
//                  showSettingsAlert();
                    canGetLocation = false;

                }


            }

        } catch (Exception e) {
        }
        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                // 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.
                return;
            }
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext,AlertDialog.THEME_HOLO_LIGHT);

        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Please turn ON GPS.");

        // On pressing Settings button
        alertDialog.setNeutralButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}
并将该类别用作—

GPSTracker gps = new GPSTracker(CLASSNAME.this);
 double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
编辑

请将此添加到您的清单文件中

 <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

**我知道您想要用户的当前Lat和Long,上述使用GPS的方法效率不高。
试着用这个来获得长和宽**
私人GoogleapClient MGoogleapClient;
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mLocationRequest=LocationRequest.create()
.setPriority(定位请求。优先级高精度)
.setInterval(10*1000)//10秒,以毫秒为单位
.setFastTestInterval(1*1000);//1秒,以毫秒为单位
公共类YourActivity扩展了AppCompact实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener{
@凌驾
未连接的公共空间(捆绑包){
Location Location=LocationServices.FusedLocationApi.getLastLocation(mgoogleapClient);
if(位置==null){
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
否则{
手柄位置(位置);
}
}
@凌驾
公共空间连接暂停(int i){
Log.i(标签“位置服务已暂停。请重新连接”);
}
@凌驾
受保护的void onResume(){
super.onResume();
setupmapifneed();
mGoogleApiClient.connect();
}
@凌驾
受保护的void onPause(){
super.onPause();
if(mgoogleapClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
if(connectionResult.hasResolution()){
试一试{
//启动尝试解决错误的活动
connectionResult.StartResult解决方案(这是连接失败解决方案请求);
}catch(IntentSender.sendtintentexe){
e、 printStackTrace();
}
}否则{
Log.i(标记,“位置服务连接失败,代码为”+connectionResult.getErrorCode());
}
@凌驾
已更改位置上的公共无效(位置){
手柄位置(位置);
}
为此创建一个服务。 其功能将是获得lat和lng

public class Location_Service extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {


private Handler handler = new Handler();


private GoogleApiClient mGoogleApiClient;

private LocationRequest mLocationRequest;



public static final String BROADCAST_ACTION = "Hello World";

private static final int TWO_MINUTES = 2;
public MyLocationListener listener;
public Location previousBestLocation = null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    intent = new Intent(BROADCAST_ACTION);
    mGoogleApiClient.connect();


    return START_STICKY;
}


@Override
public void onCreate() {
    super.onCreate();


}


@Override
public IBinder onBind(Intent intent) {


    return null;
}

@Override
public void onConnected(Bundle bundle) {

    if (mGoogleApiClient.isConnected()) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000); // Update location every second
        listener = new MyLocationListener();
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, listener);
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public class MyLocationListener implements LocationListener {

    public void onLocationChanged(final Location loc) {
        //    Log.i("**************************************", "Location changed");
        if (isBetterLocation(loc, previousBestLocation)) {
       //     Log.e("Lat/Long : ", "" + loc.getLatitude() + "/" + loc.getLongitude());
            //  Log.d("Provider : ", "" + loc.getProvider());

            Utils._LATITUDE = Double.parseDouble(String.valueOf(loc.getLatitude()));
            Utils._LONGITUDE = Double.parseDouble(String.valueOf(loc.getLongitude()));


        }
    }


}

protected boolean isBetterLocation(Location location,
                                   Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return true;
    }
    return false;
}

/**
 * Checks whether two providers are the same
 */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
   }
}
公共类位置\u服务扩展服务实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener{
私有处理程序=新处理程序();
私人GoogleapClient MGoogleapClient;
私人位置请求mLocationRequest;
公共静态最终字符串广播\u ACTION=“Hello World”;
专用静态最终整数两分钟=2;
公共MyLocationListener;
公共位置previousBestLocation=null;
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
mgoogleapclient=新的Googleapclient.Builder(此)
.addApi(LocationServices.API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
意图=新意图(广播行动);
mGoogleApiClient.connect();
返回开始时间;
}
@凌驾
public void onCreate(){
super.onCreate();
}
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
未连接的公共空间(捆绑包){
if(mgoogleapClient.isConnected()){
mLocationRequest=LocationRequest.create();
mLocationRequest.setPriority(位置请求.优先级高精度);
mlLocationRequest.setInterval(10000);//每秒更新一次位置
listener=新的MyLocationListener();
LocationServices.FusedLocationApi.RequestLocationUpdate(
mGoogleApiClient、mLocationRequest、侦听器);
}
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
}
公共类MyLocationListener实现LocationListener{
位置更改后的公共无效(最终位置loc){
//Log.i(“地点变更”);
if(isBetterLocation(loc,先前最佳位置)){
//Log.e(“Lat/Long:”,“+loc.getLatitude()+”/“+loc.getLatitude());
//Log.d(“Provider:”,“+loc.getProvider());
Utils._LATITUDE=Double.parseDouble(String.valueOf(loc.getLatitude());
Utils._longide=Double.parseDouble(String.valueOf(loc.getlongide());
}
}
}
受保护的布尔值isBetterLocation(位置,
位置(当前最佳位置){
如果(currentBestLocation==null){
//新位置总比没有位置好
返回true;
}
//检查新的位置修复程序是较新的还是较旧的
long-timeDelta=location.getTime()-currentBestLocation.getTime();
布尔值isSignificantlyNewer=时间增量>两分钟;
布尔值Issignificantlolder=时间增量<-2_分钟;
布尔值isNewer=timeDelta>0;
//如果距离当前位置已超过两分钟,请使用
//新地点
//因为用户可能已经移动了
如果(非常重要){
返回true;
//如果新位置早于两分钟,则必须
//更糟
}else if(Issignificantlolder){
返回fals
public class Location_Service extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {


private Handler handler = new Handler();


private GoogleApiClient mGoogleApiClient;

private LocationRequest mLocationRequest;



public static final String BROADCAST_ACTION = "Hello World";

private static final int TWO_MINUTES = 2;
public MyLocationListener listener;
public Location previousBestLocation = null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    intent = new Intent(BROADCAST_ACTION);
    mGoogleApiClient.connect();


    return START_STICKY;
}


@Override
public void onCreate() {
    super.onCreate();


}


@Override
public IBinder onBind(Intent intent) {


    return null;
}

@Override
public void onConnected(Bundle bundle) {

    if (mGoogleApiClient.isConnected()) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000); // Update location every second
        listener = new MyLocationListener();
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, listener);
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public class MyLocationListener implements LocationListener {

    public void onLocationChanged(final Location loc) {
        //    Log.i("**************************************", "Location changed");
        if (isBetterLocation(loc, previousBestLocation)) {
       //     Log.e("Lat/Long : ", "" + loc.getLatitude() + "/" + loc.getLongitude());
            //  Log.d("Provider : ", "" + loc.getProvider());

            Utils._LATITUDE = Double.parseDouble(String.valueOf(loc.getLatitude()));
            Utils._LONGITUDE = Double.parseDouble(String.valueOf(loc.getLongitude()));


        }
    }


}

protected boolean isBetterLocation(Location location,
                                   Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return true;
    }
    return false;
}

/**
 * Checks whether two providers are the same
 */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
   }
}
    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />