Finding Current Location in android

后端 未结 5 1331
再見小時候
再見小時候 2021-01-24 13:51

I am trying to find current location, and this is my code.

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


        
相关标签:
5条回答
  • 2021-01-24 13:53
    Location location =new Location(mlocManager.GPS_PROVIDER); 
    

    after writing this statement if you put your cursor over Location You will come to know extact meaning of this statement.

    As per Google Doc

    above Constructs a new Location. By default, time, latitude, longitude, and numSatellites are 0; hasAltitude, hasSpeed, and hasBearing are false; and there is no extra information.

    You need to fire requestLocationUpdate to get Lat & lon(If any).

    Also since you are running this example on Emulator.You will need to emulate send Lat & Lon manually.

    enter image description here

    0 讨论(0)
  • Make sure you are running the app in the real device not in the emulator. Also your device should be data enabled.

    Also give uses:permission in the Menifest file. FINE_LOCATION

    0 讨论(0)
  • 2021-01-24 14:07

    I think what you meant to do was this

    Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    

    But please note that this will only work if your gps has already grabbed a previous location. So on the emulator you will need to send a location BEFORE this line is called, and on a real device the gps will have to have been activated before the line and have received a location.

    0 讨论(0)
  • 2021-01-24 14:14

    Try this...

    package com.ShowLocationActivity;
     import java.util.List;
     import java.util.Locale;
     import android.app.Activity;
     import android.content.Context;
     import android.location.Address;
     import android.location.Criteria;
     import android.location.Geocoder;
     import android.location.Location;
     import android.location.LocationListener;
     import android.location.LocationManager;
     import android.os.Bundle;
     import android.widget.TextView;
     import android.widget.Toast;
    
    
      public class ShowLocationActivity extends Activity implements LocationListener{
    private TextView latituteField;
    private TextView longitudeField;
    private TextView placeName;
    private LocationManager locationManager;
    private String provider;
    
    @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);
        placeName=(TextView) findViewById(R.id.TextView06); 
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
    
        if (location != null) {
        //  Toast.makeText(this, String.valueOf("Provider " + provider + " has been selected."), 600).show();
            latituteField.setText(String.valueOf(location.getLatitude()));
            longitudeField.setText(String.valueOf(location.getLongitude()));
        } else {
            latituteField.setText("Provider not available");
            longitudeField.setText("Provider not available");
        }
    
        try {
            Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
            List<Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses.isEmpty()) {
                placeName.setText("Waiting for Location");
            }
            else {
                if (addresses.size() > 0) {
                    placeName.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
                }
            }
        }
        catch(Exception e){
            Toast.makeText(this, "No Location Name Found", 600).show();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }
    
    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        latituteField.setText(String.valueOf(location.getLatitude()));
        longitudeField.setText(String.valueOf(location.getLongitude()));
    
        try {
            Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
            List<Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses.isEmpty()) {
                placeName.setText("Waiting for Location");
            }
            else {
                if (addresses.size() > 0) {
                    placeName.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
                }
            }
        }
        catch(Exception e){
            Toast.makeText(this, "No Location Name Found", 600).show();
        }
    }
    
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Enabled new provider " + provider,Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    
    }
    

    }

    Here is the Xml File

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:orientation="horizontal" >
    
        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="5dip"
            android:text="Latitude: "
            android:textSize="20dip" >
        </TextView>
    
        <TextView
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="unknown"
            android:textSize="20dip" >
        </TextView>
    </LinearLayout>
    
    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    
        <TextView
            android:id="@+id/TextView03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="5dip"
            android:text="Longitute: "
            android:textSize="20dip" >
        </TextView>
    
        <TextView
            android:id="@+id/TextView04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="unknown"
            android:textSize="20dip" >
        </TextView>
    </LinearLayout>
    
    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    
        <TextView
            android:id="@+id/TextView05"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="5dip"
            android:text="Place Name "
            android:textSize="20dip" >
        </TextView>
    
        <TextView
            android:id="@+id/TextView06"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="unknown"
            android:textSize="20dip" >
        </TextView>
    </LinearLayout>
    

    Here is the manifest file

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ShowLocationActivity"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-permission android:name="android.permission.INTERNET"></uses-permission>
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> 
       <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ShowLocationActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
    

    Works for me.. try this, it will work for u 2.... :)

    0 讨论(0)
  • 2021-01-24 14:20

    Location is acquired asynchronously. You need to register a LocationListener with your LocationManager, whose onLocationChanged(Location l) will be called whenever a new location information is available.

    0 讨论(0)
提交回复
热议问题