Android GPS跟踪器始终返回0.0

时间:2016-10-27 09:31:50

标签: java android gps

我正在使用经典的GPS跟踪器代码来检索我当前的位置,但我总是得到0作为lat和lon的回报,即使我尝试改变位置仍然总是0.请注意我已经使用了以下代码在预览应用程序中,它的工作原理。

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.apostolis.map1sttest">

    <!-- Permition list bellow !-->
    <uses-permission android:name="android.permission.INTERNET" />  <!-- internet -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- internet 3g/4g enabled-->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- Google accounts -->
    <uses-permission android:name="android.permission.NETWORK" /> <!-- internet -->
    <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- Google acconts -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <!-- phone info -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- GPS -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- GPS -->
    <uses-feature android:name="android.hardware.location.gps" /> <!-- GPS (needed for android 5.0+) -->
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

GPStracker.java

    package com.example.apostolis.map1sttest;

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    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.widget.Toast;

    /**
     * Created by Apostolis on 10/27/2016.
     */


    public class GPStracker  extends Service implements LocationListener {

        private final Context context;

        boolean isGPSEnabled = false;
        boolean isNetworkEnabled = false;
        boolean canGetLocation = false;

        Location location;

        double latitude;
        double longituzzde;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
        private static final long MIN_TIME_BW_UPDATES = 100;

        protected LocationManager locationManager;

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

        public Location getLocation(){
            try {
                locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE);
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkEnabled = locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);


                if(!isGPSEnabled && !isGPSEnabled) {

                } else {
                    this.canGetLocation = true;

                    if(isNetworkEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);


                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();

                            }
                        }
                    }
                    if(isGPSEnabled) {
                        if(location == null) {
                            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            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;
        }

        public void stopUsingGPS(){
            if(locationManager != null) {
                locationManager.removeUpdates(GPStracker.this);
            }
        }

        public double getLatitude() {
            if(location != null) {
                latitude = location.getLatitude();
            }
            return latitude;
        }

        public double getLongitude(){
            if(location != null) {
                longitude = location.getLongitude();
            }
            return longitude;
        }

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        public void showSettingsAlert(){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

            alertDialog.setTitle("GPS SETTINGS");

            alertDialog.setMessage("GPS is not enabled.Go to Settings menu and enable it?");
            alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    context.startActivity(intent);
                }
            }) ;
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            alertDialog.show();
        }

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

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

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

MainActivity.java

package com.example.apostolis.map1sttest;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    GPStracker gps;
    private String lat,lon;
    Button btnGetLocation;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private double mCurrentLatitude,mCurrentLongitude;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnGetLocation = (Button) findViewById(R.id.btgps);
        //creating onClick listener for GPS.
        btnGetLocation.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {

                gps = new GPStracker(MainActivity.this);
                if (gps.canGetLocation()) {
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                    lat = Double.toString(latitude);
                    lon = Double.toString(longitude);
                    Toast.makeText(MainActivity.this,
                            "Your Location is: Lat: " + lat.toString() + " Lon:" + lon.toString(), Toast.LENGTH_LONG).show();


                } else {
                    gps.showSettingsAlert();
                }

            }

            });
    };

    @Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);

        } else {

            mCurrentLatitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            Toast.makeText(this,  mCurrentLongitude + " * ********"+mCurrentLatitude, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.apostolis.map1sttest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/btgps" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

在您的活动中,并在覆盖方法中使用以下代码

@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

if (location == null) {
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);

} else {

    Toast.makeText(this,  location.getLatitude() + " * ********"+location.getLongitude(), Toast.LENGTH_LONG).show();
}
}

创建变量

private LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;

在onCreate方法

中添加此内容
mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .build();

并在onResume

中添加
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
        Log.e("Google API", "Connecting");
        mGoogleApiClient.connect();
    }
相关问题