无法检索位置,应用崩溃

时间:2015-11-28 14:54:40

标签: java android

我有两节课。

MainActivity:

    package ytu.ytu1;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private Button gpsBtn;
    private TextView gpsTxt;
    private LocationManager locMngr;
    private LocationListener locLstnr;
GPSTracker gps;
    double lot,lat;
String txt;

    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main);

        lat=gps.getLocation().getLongitude();
        lot=gps.getLocation().getLatitude();

        txt="longti "+lat + "latit " +lot;
        gpsTxt = (TextView) findViewById(R.id.gpsTxt);
        gpsTxt.setText("Coordinates: ");
gpsTxt.append(txt);
        Toast.makeText(MainActivity.this,txt,
                Toast.LENGTH_LONG).show();

    }}

GPSTracker.java来自这里 http://pastie.org/9300205

只有权限被更改,因为我在Android kitkat平板电脑上使用它。

 package ytu.ytu1;

/**
 * Created by mia on 11/28/2015.
 */
import android.Manifest;
import android.annotation.TargetApi;
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.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {
    private final Context mContext;
private TextView txt;
    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = 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 = 0; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 5000; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

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

    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void StoprequestUpdates() {
        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);



        if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,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.


        if (isGPSEnabled) {
            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 (isNetworkEnabled) {
            if (location == null) {
                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();
                    }
                }
            }
        }
            return;
        } else {

        }
    }


    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;
                // First get location from Network Provider
                // if GPS Enabled get lat/long using GPS Services
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                        PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
                        PackageManager.PERMISSION_GRANTED) {

                if (isGPSEnabled) {
                    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 (isNetworkEnabled) {
                    if (location == null) {
                        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();
                            }
                        }
                    }
                }

            }

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


    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
            locationManager.removeUpdates(GPSTracker.this);return;}
        }
    }

    /**
     * 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);

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

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

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

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

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

    @Override
    public void onLocationChanged(Location location) {

        if (location != null) {
            this.location = location;
            latitude = location.getLatitude();
            longitude = location.getLongitude();

        }
    }

    @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;
    }

}

我甚至无法调试,一旦启动,它就会崩溃而不显示任何视图。

logcat的:

  11-28 16:51:19.541 9413-9413/? D/dalvikvm: Late-enabling CheckJNI
11-28 16:51:19.591 9413-9413/? D/ActivityThread: handleBindApplication:ytu.ytu1
11-28 16:51:19.621 9413-9413/ytu.ytu1 W/ApplicationPackageManager: getCSCPackageItemText()
11-28 16:51:19.631 9413-9413/ytu.ytu1 D/DisplayManager: DisplayManager()
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17904: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17908: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.661 9413-9413/ytu.ytu1 D/AndroidRuntime: Shutting down VM
11-28 16:51:19.661 9413-9413/ytu.ytu1 W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416adbc0)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: FATAL EXCEPTION: main
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Process: ytu.ytu1, PID: 9413
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{ytu.ytu1/ytu.ytu1.MainActivity}: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:166)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5584)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:  Caused by: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at ytu.ytu1.MainActivity.onCreate(MainActivity.java:44)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:5447)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:166) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5584) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method) 

我在android studio上使用,我没有改变原始代码。我不明白为什么它不会开始。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

GPSTracker gps = new GPSTracker(this);

还请查看本教程:http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/