GPS关闭时谷歌地图崩溃(请求位置)

时间:2014-06-04 18:02:59

标签: android google-maps crash gps

我试图管理这样的事情:

如果GPS已关闭,请不要执行任何操作,如果已打开,请将相机放大到用户所在位置。然后,在位置按钮上,如果它被点击并且GPS关闭,则将其链接到设置活动(当然是Android);然后如果再次点击它会放大。

否则,如果它已开启,则放大。

问题是,如果我打开应用程序并且GPS关闭,它会立即崩溃,但如果GPS打开则可以正常工作。

我需要更改/添加到我的代码才能使其正常工作?

MainActivity:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends Activity implements LocationListener {
    GoogleMap map;
    public double longitude;
    public double latitude;

    Location location;

    @SuppressWarnings("unused")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.setMyLocationEnabled(true);

        final Criteria criteria = new Criteria();

        final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.getBestProvider(criteria, true);

        final Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        if (location != null) {
            LatLng UserLoc = new LatLng(latitude, longitude);
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(UserLoc, 7));
        } else {
            Toast.makeText(getApplicationContext(), "cant get loc", Toast.LENGTH_LONG).show();
        }


        map.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
                // if the Gps is off it openes a dialog to turn it off
                if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    buildAlertMessageNoGps();
                } else if (location == null) {
                    Toast.makeText(getApplicationContext(), "cant get loc", Toast.LENGTH_LONG).show();
                } else {
                    // if it on, animates to the current position
                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15));
                    return false;
                }
                return false;
            }
        });
    }

    public void TurnOnGps(){
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        setUpMapIfNeeded();
        super.onResume();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the
        // map.
        if (map == null) {
            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            if (map != null) {
            }
        }
    }

    // function that opened an activity to turn on the GPS
    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("GPS is off ")
                .setCancelable(true)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog, final int id) {
                                startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

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

}

我的LogCat:

06-04 20:48:44.811: E/AndroidRuntime(11489): FATAL EXCEPTION: main
06-04 20:48:44.811: E/AndroidRuntime(11489): java.lang.RuntimeException: Unable to start activity ComponentInfo{nir.rauch.flantir/nir.rauch.flantir.MainActivity}: java.lang.NullPointerException
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.os.Looper.loop(Looper.java:137)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.ActivityThread.main(ActivityThread.java:5419)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at java.lang.reflect.Method.invokeNative(Native Method)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at java.lang.reflect.Method.invoke(Method.java:525)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at dalvik.system.NativeStart.main(Native Method)
06-04 20:48:44.811: E/AndroidRuntime(11489): Caused by: java.lang.NullPointerException
06-04 20:48:44.811: E/AndroidRuntime(11489):    at nir.rauch.flantir.MainActivity.onCreate(MainActivity.java:45)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.Activity.performCreate(Activity.java:5372)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
06-04 20:48:44.811: E/AndroidRuntime(11489):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
06-04 20:48:44.811: E/AndroidRuntime(11489):    ... 11 more

我已尝试在OnCreate功能中执行if else语句(如果启用了GPS或未启用GPS),但它没有找到该位置。

1 个答案:

答案 0 :(得分:4)

final Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

latitude = location.getLatitude(); // <--
longitude = location.getLongitude(); // <--

if (location != null) {

这两行不应该进入if语句吗?