通过Android应用即时获取GPS位置

时间:2011-05-20 07:10:31

标签: android android-emulator gps android-location

所有。我正在写一个关于GPS位置的Android应用程序。

我在模拟器上尝试过并手动输入纬度和经度,它工作正常。 但是,我的问题是:在真实设备上,在调试模式下,只有在改变位置时才能通过使用意图去下一个类。如果我直接启动应用程序,我可以看到闪烁的GPS图标,但应用程序将只停留在此处,并且不会启动下一个活动。似乎永远不会改变onLocationChanged()中的变量。

我听说过立即获取位置是使用getLastKnownLocation()方法。但我没能到达应该使用它的地方。

这是我使用LocationManager获取位置的类。

有什么解决方案吗?我很困惑。非常感谢!!

    public class mainMenu extends Activity{

private LocationManager locationManager = null;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);




    Button button1 = (Button)findViewById(R.id.button1);
    button1.setOnClickListener(new OnClickListener(){
        public void onClick(View v){

            Intent i3 = new Intent();
            i3.setClass(mainMenu.this, police.class);
            i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mainMenu.this.startActivityForResult(i3,0);


        }
    });

    Button button2 = (Button)findViewById(R.id.button2);
    button2.setOnClickListener(new OnClickListener(){
        public void onClick(View v){

            Intent i3 = new Intent();
            i3.setClass(mainMenu.this, ambulance.class);
            i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mainMenu.this.startActivityForResult(i3,0);


        }
    });

    Button button3 = (Button)findViewById(R.id.button3);
    button3.setOnClickListener(new OnClickListener(){
        public void onClick(View v){

            Intent i3 = new Intent();
            i3.setClass(mainMenu.this, fire_station.class);
            i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mainMenu.this.startActivityForResult(i3,0);


        }
    });



        locationManager = (LocationManager)mainMenu.this.getSystemService(Context.LOCATION_SERVICE);

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000 , 0, new MyLocationUpdater());

        String provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);



}



public class MyLocationUpdater implements LocationListener{ //change location interface
    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
    //          store the location data
    //          get the best record



        Double lat = location.getLatitude();
        Double lon = location.getLongitude();

        System.out.println("The latitude is " + lat + "and " 
                + "the longitude is "+ lon);


        Double lat11 = lat - 1/69.0;
        Double lat12 = lat + 1/69.0;
        Double lon11 = lon - 1/42.0;
        Double lon12 = lon + 1/42.0;

        StaticVariables.latS1 = lat11.toString();
        StaticVariables.latN1 = lat12.toString();
        StaticVariables.lonW1 = lon11.toString();
        StaticVariables.lonE1 = lon12.toString();

        Double lat111 = lat - 2/69.0;
        Double lat121 = lat + 2/69.0;
        Double lon111 = lon - 2/42.0;
        Double lon121 = lon + 2/42.0;

        StaticVariables.latS11 = lat111.toString();
        StaticVariables.latN11 = lat121.toString();
        StaticVariables.lonW11 = lon111.toString();
        StaticVariables.lonE11 = lon121.toString();

    //          ==================================================
    //          ambulances

        Double lat21 = lat - 3/69.0;
        Double lat22 = lat + 3/69.0;
        Double lon21 = lon - 3/42.0;
        Double lon22 = lon + 3/42.0;

        StaticVariables.latS2 = lat21.toString();
        StaticVariables.latN2 = lat22.toString();
        StaticVariables.lonW2 = lon21.toString();
        StaticVariables.lonE2 = lon22.toString();

        Double lat211 = lat - 5.5/69.0;
        Double lat221 = lat + 5.5/69.0;
        Double lon211 = lon - 5.5/42.0;
        Double lon221 = lon + 5.5/42.0;

        StaticVariables.latS21 = lat211.toString();
        StaticVariables.latN21 = lat221.toString();
        StaticVariables.lonW21 = lon211.toString();
        StaticVariables.lonE21 = lon221.toString();

    //          ===================================================
    //          fire stations

        Double lat31 = lat - 2/69.0;
        Double lat32 = lat + 2/69.0;
        Double lon31 = lon - 2/42.0;
        Double lon32 = lon + 2/42.0;

        StaticVariables.latS3 = lat31.toString();
        StaticVariables.latN3 = lat32.toString();
        StaticVariables.lonW3 = lon31.toString();
        StaticVariables.lonE3 = lon32.toString();

        Double lat311 = lat - 2/69.0;
        Double lat321 = lat + 2/69.0;
        Double lon311 = lon - 2/42.0;
        Double lon321 = lon + 2/42.0;

        StaticVariables.latS31 = lat311.toString();
        StaticVariables.latN31 = lat321.toString();
        StaticVariables.lonW31 = lon311.toString();
        StaticVariables.lonE31 = lon321.toString();

        Intent intent = new Intent();
        intent.setClass(mainMenu.this, getPhoneNumber.class);
        mainMenu.this.startActivity(intent);
    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }
}

    }

4 个答案:

答案 0 :(得分:3)

getLastKnownLocation方法不会触发onLocationChanged事件。重构代码的一种方法是将作用于Location的逻辑移动到单独的方法,然后在调用getLastKnownLocation之后以及从onLocationChanged方法调用该方法。

请注意,无法保证getLastKnownLocation会提供有意义的Location,因为自上次更新位置后设备可能已移动。

示例代码:

public void onCreate(Bundle savedInstanceState){
    ....
    String provider = LocationManager.GPS_PROVIDER;
    Location location = locationManager.getLastKnownLocation(provider);
    updateLocation(location);
}

public class MyLocationUpdater implements LocationListener{ //change location interface
    @Override
    public void onLocationChanged(Location location) {
        updateLocation(location);
    }
    ...
}

void updateLocation(Location location) {
    Double lat = location.getLatitude();
    Double lon = location.getLongitude();

    // the rest of the code from onLocationChanged
}

答案 1 :(得分:0)

与GPS卫星建立连接后,

getLastKnownLocation()速度更快。这是第一次,它将返回null,或者没有值,直到没有建立连接。 您可以添加GpsListener以了解何时获取位置。搜索“如何获得gps修复”,您可能会回答您的问题

答案 2 :(得分:0)

我之前遇到同样的问题..但我有解决方案..这是立即获取位置的最简单方法。

public class LocationFinder extends Activity {

    TextView textView1;
    Location currentLocation;
    double currentLatitude,currentLongitude;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textView1 = (TextView) findViewById(R.id.textView1);
        Log.i("@@@@@@@@@@ Inside LocationFinder onCreate", "LocationFinder onCreate");

        FindLocation();

    }

    public void FindLocation() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                updateLocation(location);

                Toast.makeText(
                        LocationFinder.this,
                        String.valueOf(currentLatitude) + "\n"
                                + String.valueOf(currentLongitude), 5000)
                        .show();

                }

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

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }


    void updateLocation(Location location) {
            currentLocation = location;
            currentLatitude = currentLocation.getLatitude();
            currentLongitude = currentLocation.getLongitude();
            textView1.setText(String.valueOf(currentLatitude) + "\n"
                    + String.valueOf(currentLongitude));

        }
}

不要忘记在Manifeast中给予许可。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>

答案 3 :(得分:-1)

public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
 public LocationManager mLocManager;
// *******This is the new Code start on 11/4/2011 at 3 o'clock


/**
 * This is the Home Button if user Login then it is move to TennisAppActivity otherwise move to Login  
 *
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    mContext=this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homelayout);


    mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            this);
    mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
            0, this);
    locationUpdate();
    ((Button) this.findViewById(R.id.ButtonHome))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {

                        startActivity(new Intent(HomeActivity.this,
                                DefaultDisplay.class));

                }
            });

    ((Button) this.findViewById(R.id.ButtonProfile))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                MyProfile.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","MyProfile");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonNotifications))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                ShowAllNotificationActiviry.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","ShowAllNotificationActiviry");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonFavorites))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                FavoritesActivity.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","FavoritesActivity");
                        startActivity(intent);
                    }
                }
            });

            ((Button) this.findViewById(R.id.ButtonMore))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                        startActivity(new Intent(HomeActivity.this,
                                MoreListActivity.class));
                }
            });

}

public void locationUpdate()
{
    CellLocation.requestLocationUpdate();
}


public void getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String add = obj.getAddressLine(0);
        GUIStatics.currentAddress = obj.getSubAdminArea() + ","
                + obj.getAdminArea();
        GUIStatics.latitude = obj.getLatitude();
        GUIStatics.longitude = obj.getLongitude();
        GUIStatics.currentCity= obj.getSubAdminArea();
        GUIStatics.currentState= obj.getAdminArea();
        add = add + "\n" + obj.getCountryName();
        add = add + "\n" + obj.getCountryCode();
        add = add + "\n" + obj.getAdminArea();
        add = add + "\n" + obj.getPostalCode();
        add = add + "\n" + obj.getSubAdminArea();
        add = add + "\n" + obj.getLocality();
        add = add + "\n" + obj.getSubThoroughfare();

        Log.v("IGA", "Address" + add);
        // Toast.makeText(this, "Address=>" + add,
        // Toast.LENGTH_SHORT).show();

        // TennisAppActivity.showDialog(add);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}



public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    GUIStatics.latitude=location.getLatitude();
    GUIStatics.longitude= location.getLongitude();
    Log.v("Test", "IGA" + "Lat" + latitude + "   Lng" + longitude);
    //mLocManager.r

    getAddress(latitude, longitude);
    if(location!=null)
    {

    mLocManager.removeUpdates(this);
    }
    // Toast.makeText(this, "Lat" + latitude + "   Lng" + longitude,
    // Toast.LENGTH_SHORT).show();
}


public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
}


public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}


public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
     if(arg1 == 
            LocationProvider.TEMPORARILY_UNAVAILABLE) { 
                                    Toast.makeText(HomeActivity.this, 
            "LocationProvider.TEMPORARILY_UNAVAILABLE", 
            Toast.LENGTH_SHORT).show(); 
                        } 
                        else if(arg1== LocationProvider.OUT_OF_SERVICE) { 
                                    Toast.makeText(HomeActivity.this, 
            "LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show(); 
                        } 

}

}

这是我用它来查找借助纬度和经度的设备位置的代码,我们还在此代码中调用了getLastLocationUpdate。 我希望这对你很有帮助。