0

場所の緯度と経度を見つけるためのコードを書きました。Eclipse を使用している PC では問題なく動作しますが、Android フォンでは動作しません。

public class MainActivity extends Activity {

    protected LocationManager locationManager;
    protected Button retrieveLocationButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1,
                1000, new MyLocationListener());
        retrieveLocationButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showCurrentLocation();
            }
        });
    }

    protected void showCurrentLocation() {
        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude());
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG)
                    .show();
        }
    }

    private class MyLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude());
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG)
                    .show();
        }

        public void onStatusChanged(String s, int i, Bundle b) {
            Toast.makeText(MainActivity.this, "Provider status changed",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderDisabled(String s) {
            Toast.makeText(MainActivity.this,
                    "Provider disabled by the user. GPS turned off",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String s) {
            Toast.makeText(MainActivity.this,
                    "Provider enabled by the user. GPS turned on",
                    Toast.LENGTH_LONG).show();
        }
    }

}
4

1 に答える 1

1

AndroidManifest ファイルで gps にアクセスするために必要なすべての権限を与えていることを確認してください...

android.permission.ACCESS_COARSE_LOCATION
android.permission.ACCESS_FINE_LOCATION
android.permission.READ_PHONE_STATE
android.permission.INTERNET

このリンクを参照してください: https://sites.google.com/site/androidhowto/how-to-1/using-the-gps

于 2012-08-08T10:14:55.517 に答える