简体   繁体   English

获取Android中的当前位置

[英]get current location in android

I have tried following code but not getting current location. 我尝试了以下代码,但未获取当前位置。
When I manual set location at emulator control then I get such location but not getting current location .I get null location. 当我在模拟器控制中手动设置位置时,我会得到这样的位置,但没有得到当前位置。我得到的是空位置。

  • How to get current location? 如何获得当前位置?
  • Is there any other way to get current location? 还有其他方法可以获取当前位置吗?

This is my code: 这是我的代码:

package com.p;
import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
    public class GooglemapActivity extends Activity implements LocationListener {
   private TextView latituteField;
   private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;
        EditText t;
   @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
     locationManager =                  (LocationManager)getSystemService(Context.LOCATION_SERVICE);



    // Define the criteria how to select the locatioin provider -> use
    // default

            Criteria criteria = new Criteria();
           criteria.setAccuracy(Criteria.ACCURACY_FINE);
           criteria.setAltitudeRequired(false);//true if required
           criteria.setBearingRequired(false);//true if required
           criteria.setCostAllowed(true);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            provider = locationManager.getBestProvider(criteria, true);
            //provider=LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
             /*check provder*/boolean statusOfGPS    =locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);


            if ( statusOfGPS==true) {
        // Initialize the location fields
        if (location != null) {
               System.out.println("Provider " + provider + " has been      selected.");
                   double lat = (double) (location.getLatitude());
                    double lng = (double) (location.getLongitude());
                   latituteField.setText(Double.toString(lat));
                    longitudeField.setText(Double.toString(lng));
                } else {
                      latituteField.setText("Provider is not available");
                      longitudeField.setText("Provider not available");
                }


        }
        else
        {

        latituteField.setText("eeeeeeeee");
        longitudeField.setText("rrrrrrrrr");

        }
    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
    locationManager.removeUpdates(this);
    }

    public void onLocationChanged(Location location) {
            double lat = (double) (location.getLatitude());
         double lng = (double) (location.getLongitude());
        latituteField.setText(Double.toString(lat));
        longitudeField.setText(Double.toString(lng));
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();

    }

    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
            Toast.LENGTH_SHORT).show();
    }
     }

I have added permissions in manifest.xml as below: 我在manifest.xml中添加了权限,如下所示:

<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"/>

You won't get current location in emulator. 您不会在模拟器中获得当前位置。 You can set them through DDMS, and they will be your current location in case of a emulator. 您可以通过DDMS设置它们,如果有模拟器,它们将是您当前的位置。

Please, don't try to get last-known-location, most of the time it's stale and useless. 请不要尝试获取最后一个已知位置,在大多数情况下,它是陈旧且无用的。 Set up locationListener instead and wait for the location updates. 而是设置locationListener并等待位置更新。 This will get you your current location. 这将为您提供当前位置。

You may use this code to start listing for GPS updates and do something with the data you receive. 您可以使用此代码开始列出GPS更新信息,并对收到的数据进行处理。 It also prints messages in the log file for easy debugging. 它还在日志文件中打印消息,以便于调试。 Please, note, this function does not return any results, it only starts listening to GPS . 请注意, 此功能不会返回任何结果,它只会开始收听GPS Results will be provided some time later in // do something here with the new location data part, when you may save them somewhere. 当您可以将结果保存在某处时,稍后会在// do something here with the new location data部分// do something here with the new location data提供结果。

private void getGpsData() {
    locationManager = (LocationManager) owner.getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.i(TAG, "location change:" + location.toString());

            String longitude = "Londitude: " + location.getLongitude();
            String latitude = "Latitude: " + location.getLatitude();

            if( location.hasAccuracy() ) {  // good enough?
                // do something here with the new location data
                ....
                //
                Log.i(TAG, "GPS listener done");
                locationManager.removeUpdates(this);    // don't forget this to save battery
            }
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.i(TAG, provider + " status:" + status);
        }

        public void onProviderEnabled(String provider) {
            Log.i(TAG, provider + " enabled");
        }

        public void onProviderDisabled(String provider) {
            Log.i(TAG, provider + " disabled");
        }
    };
    Log.i(TAG,"GPS listener started");
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM