当检索一个真正的Andr​​oid手机上运行的GPS坐标不工作坐标、机上、工作、Andr

2023-09-08 08:49:56 作者:闹够了就滚

我的计划应该能够:

更改地图放大到手机的当前位置添加标记显示纬度的警报和经度值

当我使用GPS_PROVIDER,功能1-4作品在我的模拟器(因为我手动给它一个经度和纬度值)。但是,当我创建了一个APK文件,2-4功能不起作用。

When I use GPS_PROVIDER, functions 1-4 works in my emulator (because I manually feed it a latitude and longitude values). But when I created an apk file, 2-4 functions don't work.

下面是我的课。

package com.locator.map;

import java.text.DecimalFormat;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Main extends MapActivity
{
    MapController controller;
    double currentLat;
    double currentLon;
    LocationManager manager;
    boolean locationChanged = false;
    Button retrieveLocationButton, toggleViewButton;
    boolean streetview = false;
    Drawable d;
    List<Overlay> overlaylist;
    MapView map;
    Criteria criteria;
    String bestProvider;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        map = (MapView) findViewById (R.id.googleMap);       
        map.setBuiltInZoomControls(true);
        map.setSatellite(true);
        controller = map.getController();


        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        manager = (LocationManager) this.getSystemService (Context.LOCATION_SERVICE);        
        bestProvider = manager.getBestProvider(criteria, true);

        retrieveLocationButton = (Button) findViewById(R.id.retrieveLocation);
        toggleViewButton = (Button) findViewById(R.id.changeView);

        retrieveLocationButton.setOnClickListener(new OnClickListener()
        {      
                public void onClick(View v)
                {
                    showCurrentLocation();
                }
        });        

        toggleViewButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                if (streetview == false)
                {
                    map.setSatellite(false);
                    map.setStreetView(true);
                    streetview=true;
                }
                else if (streetview == true)
                {
                    map.setStreetView(false);
                    map.setSatellite(true);
                    streetview=false;
                }
            }           
        });
        LocationListener listener = new LocationListener()
        {
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub

                //Retrieve the current GPS coordinates
                currentLat = location.getLatitude();
                currentLon = location.getLongitude();

                locationChanged = true;
            }

            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Your GPS services are not activated.", Toast.LENGTH_LONG).show();
            }

            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Your GPS services are now activated.", Toast.LENGTH_LONG).show();
            }

            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Your GPS service provider is changed.", Toast.LENGTH_LONG).show();
            }

        };

        manager.requestLocationUpdates(bestProvider, 1000, 1, listener); //--> To update current location (coordinates [latitude & longitude]).       

    }

    protected void showCurrentLocation()
    {
        // TODO Auto-generated method stub

        //If location is changed or updated - Zoom in to current location, add a marker and show a dialog with current coordinates.
        if (locationChanged == true)
        {
            //Set the map's view and zoom level animation
            GeoPoint currentLocation = new GeoPoint ((int) (currentLat * 1E6), (int) (currentLon * 1E6));

            controller.setCenter(currentLocation);
            controller.setZoom(15);

            //Show the current coordinates (Convert to String and round off - 6 decimal places)
            String printLat = new DecimalFormat("0.######").format((double)currentLat);
            String printLon = new DecimalFormat("0.######").format((double)currentLon);

            AlertDialog alert = new AlertDialog.Builder(Main.this).create();
            alert.setTitle("Current Location:");
            alert.setMessage("Latitude: " + printLat + "\n" + "Longitude: " + printLon);
            alert.setButton("Close", new DialogInterface.OnClickListener()
            {               
                public void onClick(DialogInterface arg0, int arg1)
                {
                    // TODO Auto-generated method stub
                    //Alert Dialog won't work without a listener
                    //Do nothing (This will simply close your alert dialog)
                }
            });     
            alert.show();

            //Add a marker
            overlaylist = map.getOverlays();
            d = getResources().getDrawable(R.drawable.ic_launcher);         
            CustomPinpoint marker = new CustomPinpoint (d, Main.this);          
            OverlayItem overlayitem = new OverlayItem (currentLocation, "1st String", "2nd String");
            marker.insertPinpoint(overlayitem);
            overlaylist.add(marker);    
        }
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        // TODO Auto-generated method stub
        return false;
    }
}

我也使用NETWORK_PROVIDER尝试。一切工作在我的手机,但它没有返回准确的经度和纬度值。它添加了标记,但它约1公里,距我的实际位置。

I also tried using NETWORK_PROVIDER. Everything works in my phone but it's not returning accurate latitude and longitude values. It adds marker but it's about 1 kilometer away from my actual location.

下面是我用类NETWORK_PROVIDER:

Here's my class using NETWORK_PROVIDER:

package com.locator.map;

import java.text.DecimalFormat;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Main extends MapActivity
{
    MapController controller;
    double currentLat;
    double currentLon;
    LocationManager manager;
    boolean locationChanged = false;
    Button retrieveLocationButton, toggleViewButton;
    boolean streetview = false;
    Drawable d;
    List<Overlay> overlaylist;
    MapView map;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        map = (MapView) findViewById (R.id.googleMap);       
        map.setBuiltInZoomControls(true);
        map.setSatellite(true);
        controller = map.getController();


        manager = (LocationManager) this.getSystemService (Context.LOCATION_SERVICE);        

        retrieveLocationButton = (Button) findViewById(R.id.retrieveLocation);
        toggleViewButton = (Button) findViewById(R.id.changeView);

        retrieveLocationButton.setOnClickListener(new OnClickListener()
        {      
                public void onClick(View v)
                {
                    showCurrentLocation();
                }
        });        

        toggleViewButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                if (streetview == false)
                {
                    map.setSatellite(false);
                    map.setStreetView(true);
                    streetview=true;
                }
                else if (streetview == true)
                {
                    map.setStreetView(false);
                    map.setSatellite(true);
                    streetview=false;
                }
            }           
        });
        LocationListener listener = new LocationListener()
        {
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub

                //Retrieve the current GPS coordinates
                currentLat = location.getLatitude();
                currentLon = location.getLongitude();

                locationChanged = true;
            }

            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Your GPS services are not activated.", Toast.LENGTH_LONG).show();
            }

            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Your GPS services are now activated.", Toast.LENGTH_LONG).show();
            }

            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "Your GPS service provider is changed.", Toast.LENGTH_LONG).show();
            }

        };

        manager.requestLocationUpdates(NETWORK_PROVIDER, 1000, 1, listener); //--> To update current location (coordinates [latitude & longitude]).       

    }

    protected void showCurrentLocation()
    {
        // TODO Auto-generated method stub

        //If location is changed or updated - Zoom in to current location, add a marker and show a dialog with current coordinates.
        if (locationChanged == true)
        {
            //Set the map's view and zoom level animation
            GeoPoint currentLocation = new GeoPoint ((int) (currentLat * 1E6), (int) (currentLon * 1E6));

            controller.setCenter(currentLocation);
            controller.setZoom(15);

            //Show the current coordinates (Convert to String and round off - 6 decimal places)
            String printLat = new DecimalFormat("0.######").format((double)currentLat);
            String printLon = new DecimalFormat("0.######").format((double)currentLon);

            AlertDialog alert = new AlertDialog.Builder(Main.this).create();
            alert.setTitle("Current Location:");
            alert.setMessage("Latitude: " + printLat + "\n" + "Longitude: " + printLon);
            alert.setButton("Close", new DialogInterface.OnClickListener()
            {               
                public void onClick(DialogInterface arg0, int arg1)
                {
                    // TODO Auto-generated method stub
                    //Alert Dialog won't work without a listener
                    //Do nothing (This will simply close your alert dialog)
                }
            });     
            alert.show();

            //Add a marker
            overlaylist = map.getOverlays();
            d = getResources().getDrawable(R.drawable.ic_launcher);         
            CustomPinpoint marker = new CustomPinpoint (d, Main.this);          
            OverlayItem overlayitem = new OverlayItem (currentLocation, "1st String", "2nd String");
            marker.insertPinpoint(overlayitem);
            overlaylist.add(marker);    
        }
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        // TODO Auto-generated method stub
        return false;
    }
}

下面是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.locator.map"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8"  android:targetSdkVersion="8"/>
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application android:icon="@drawable/ic_launcher" android:label="Locator" >
        <uses-library android:name="com.google.android.maps" />     
        <activity
            android:name=".Main"
            android:label="Locator" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        
    </application>

</manifest>

我认为,全球定位系统是在我区在这里工作,谷歌地图应用程序返回时,我用它准确的定位。我试着用我在同一个位置,我用谷歌地图应用程序(包括NETWORK_PROVIDER和GPS_PROVIDER):

I think, GPS is working here in my area, Google Maps application returns accurate location when I use it. I tried using my application (both NETWORK_PROVIDER and GPS_PROVIDER) in the same location where I used Google Maps:

NETWORK_PROVIDER仍返回不准确的结果。 GPS_PROVIDER仍然无法正常工作。

请帮我。

推荐答案

您确定谷歌地图,因为它是者正在使用GPS?我发现,往往GMaps实现显示位置(在时间和pretty precise的!),使用从Wi-Fi和GSM antennaes唯一的数据......在这种情况下,你的code可能永远不会被调用(直到有GPS定位)。

Are you sure Google Maps is using GPS as it's provider? I find that GMaps often shows locations (and pretty precise ones at times!) using only data from Wi-Fi and GSM antennaes... In that case, your code may never be called (until there's a GPS fix).

我会尝试加入

locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener());

到code(以下注册获取GPS更新),只是为了检查这种可能性。

to your code (below the registration to get GPS updates), just to check that possibility.

修改

试着改变ACCURACY_FINE到ACCURACY_HIGH

Try changing ACCURACY_FINE to ACCURACY_HIGH