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

标签 android google-maps crash gps

我试过管理这样的事情:

如果 GPS 关闭,什么都不做,如果它打开,将相机放大到用户所在的位置。然后,在位置按钮上,如果单击它并且 GPS 关闭,则将其链接到设置 Activity (当然是 Android 的);然后如果再次单击它会放大。

否则,如果它打开,则放大。

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

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

主要 Activity :

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 是否启用),但它找不到位置。

最佳答案

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

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

if (location != null) {

这两行不应该放在 if 语句中吗?

关于android - GPS 关闭时谷歌地图崩溃(请求位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044471/

相关文章:

java - R无法解析

android - Exoplayer - 视频永远不会达到 STATE_READY

google-maps - Google Maps Api v3 - 在运行时设置 map 位置

java - 模组制作,在屏幕上绘制东西时崩溃?

android - 我应该使用什么 ruboto 调试工具?

android - 如何使用预定义的广告 SDK(如 admob 等)在我自己的 android 应用程序中实现我自己的自定义广告

ios - 如何在iOS中使用Google Place API以GMSPlaces而不是GMSAutocompletePrediction的形式获取自动完成的搜索位置结果?

android - 带有 Google Maps API v2 : mysterious black view 的 ViewPager

python - Sage/Python 中 fork 后出现 SIGILL

google-chrome - Uploadify 使 Chrome 的 Flashplayer 崩溃并生成 'Ah, snap!' 屏幕