Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/185.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 安卓GPS获取旧位置_Android - Fatal编程技术网

Android 安卓GPS获取旧位置

Android 安卓GPS获取旧位置,android,Android,我正在编写GPS追踪应用程序,我发现一个问题:有一段时间它得到了我原来的位置,当我从手机中取出电池并重新启动手机时,它工作正常。 我不知道为什么,你能帮我吗 这是获取位置的代码: public class GPSTraker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled =

我正在编写GPS追踪应用程序,我发现一个问题:有一段时间它得到了我原来的位置,当我从手机中取出电池并重新启动手机时,它工作正常。
我不知道为什么,你能帮我吗

这是获取位置的代码:

public class GPSTraker extends Service implements LocationListener {

    private final Context mContext;

    // 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 = 10; // 10 meters

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

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTraker(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);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // 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();
                            }
                        }
                    }
                }
            }

        } 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) {
            locationManager.removeUpdates(GPSTraker.this);
        }
    }

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

    public float getspeed() {
        float seeed = 0;
        if (location != null)
            seeed = location.getSpeed();
        return seeed;
    }

    /**
     * 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) {
    }

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

}
public final LocationListener LocationListener=new LocationListener()
{
已更改位置上的公共无效(位置){
Home.this.location=位置;
}
公共无效onProviderDisabled(字符串提供程序){
Home.this.location=null;
}
公共无效onProviderEnabled(字符串提供程序){
}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
};
公共字符串gpsadd(){
试一试{
如果(isGPS){
Geocoder gc=新的Geocoder(Home.this,Locale.getDefault());
尝试
{
addflg=0;
lat=位置。getLatitude();
lng=location.getLongitude();
布尔lop=真;
while(lop){
列表地址=gc.getFromLocation(lat,lng,1);
如果(地址.size()>0)
{
lop=假;
addflg=1;
地址=地址。获取(0);
s_addr=address.getAddressLine(0)+++address.getAddressLine(1)+++address.getAddressLine(2);
disp=“Location\n”+address.getAddressLine(0)+“\n”+address.getAddressLine(1)+“\n”+address.getAddressLine(2);
}
}
}
捕获(例外e)
{
e、 printStackTrace();
}
}否则{
显示(“GPS未启用”);
}
}捕获(例外e){
e、 printStackTrace();
}
返回disp;
}

有两种方法可以在Android中检索位置
1.使用
LocationManager

2.使用
LocationClient
(谷歌播放服务)

  • 使用
    LocationManager
    ,您必须提供
    LocationManager
    a
    提供商(GPS、网络、WIFI、无源)。如果是GPS提供商,
    LocationManager
    将使用硬件GPS解析当前位置。如果GPS目前不可用,您可以调用
    GetLastKnownLocation()
    。它将返回一个
    位置
    对象,该对象来自GPS捕捉到的最后一个位置(如果有),如果没有,则返回
    。如果尝试从
    getLastKnownLocation()
    获取的
    Location
    对象的
    getTime()
    方法,它将在捕获最后一个位置时返回给您。同样的事情也适用于网络、wifi或无源提供商

  • 使用google play services中的
    LocationClient
    LocationClient
    将通过调用
    getLastLocation()
    ,使用GPS、WIFI、3G(网络)*这三种设备(如果可用),自动为您提供最准确的当前
    位置。同样,这将返回一个
    位置
    对象,其余部分如上所述


  • 使用在您的应用程序中更合适的任何方法。

    注意:LocationManager将要求设备配备硬件GPS,LocationClient将要求Google play服务,GPS不是必须的,但如果设备配备GPS,则将有助于定位更加准确

    这里我给出的u代码通过GPS显示当前位置…只需复制并粘贴以下代码。。。并在你的android清单文件中定义2个权限…可能这段代码可以帮助你,如果你想要任何澄清,请通知我

    **MainActivity.java**
    
    
    package com.example.android;
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    import android.app.Activity;
    import android.location.Address;
    import android.location.Geocoder;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
    Button btnShowLocation;
    GPSTracker gps;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    
        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(MainActivity.this);
    
                // check if GPS enabled     
                if(gps.canGetLocation()){
    
    
                      double longitude = gps.getLongitude();
                     double latitude = gps.getLatitude();
    
                     getAddress(latitude, longitude);
    
    
    
                }    
    
                    else{
                            // can't get location
                            // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                         }
    
            }
                });
    }
    
    
     private void getAddress(double latitude, double longitude) {
     StringBuilder result = new StringBuilder();
     try {
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            result.append(address.getLocality()).append("\n");
            //result.append(address.getPostalCode());
            result.append(address.getAdminArea()).append("\n");
            result.append(address.getCountryName());
            String address1 = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getAddressLine(2);     
        Toast.makeText(getApplicationContext(), "Your  address is  " + address1 + " ," +   city + "," + country , Toast.LENGTH_LONG).show();
    
    
        }
     } catch (IOException e) {
        Log.e("tag", e.getMessage());
    }
         }   }
    
    Activitymain.xml

    
    
    AndroidManifest.xml

    
    
    示例代码?使用Google Play服务或位置提供商?我使用的是您实现的位置提供商代码?
    **MainActivity.java**
    
    
    package com.example.android;
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    import android.app.Activity;
    import android.location.Address;
    import android.location.Geocoder;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
    Button btnShowLocation;
    GPSTracker gps;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    
        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(MainActivity.this);
    
                // check if GPS enabled     
                if(gps.canGetLocation()){
    
    
                      double longitude = gps.getLongitude();
                     double latitude = gps.getLatitude();
    
                     getAddress(latitude, longitude);
    
    
    
                }    
    
                    else{
                            // can't get location
                            // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                         }
    
            }
                });
    }
    
    
     private void getAddress(double latitude, double longitude) {
     StringBuilder result = new StringBuilder();
     try {
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            result.append(address.getLocality()).append("\n");
            //result.append(address.getPostalCode());
            result.append(address.getAdminArea()).append("\n");
            result.append(address.getCountryName());
            String address1 = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getAddressLine(2);     
        Toast.makeText(getApplicationContext(), "Your  address is  " + address1 + " ," +   city + "," + country , Toast.LENGTH_LONG).show();
    
    
        }
     } catch (IOException e) {
        Log.e("tag", e.getMessage());
    }
         }   }
    
     package com.example.android;
     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.util.Log;
    
     public class GPSTracker extends Service implements LocationListener {
    
    private final Context mContext;
    
    // 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 = 10; // 10 meters
    
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    
    // 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);
    
            if (!isGPSEnabled && !isNetworkEnabled) {
                // 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();
    
                            }
                        }
                    }
                }
            }
    
        } 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){
            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);
    
        // 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) {
    }
    
    @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;
    }
    
     }
    
     <?xml version="1.0" encoding="utf-8"?>
     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >
    
     <Button android:id="@+id/btnShowLocation" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
    
     </RelativeLayout>
    
      <uses-permission android:name="android.permission.INTERNET"  />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />