问题
Currently I want to get the user current location of latitude and longitude but my code can get until I pressed the send button in the emulator setting but what I want is to auto get the location and set it to the textview so what should I do? Anyone please advice me to solve this problem please because I really not familiar with the location code.
Here's my code
package com.example.rex.ota30;
import android.*;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static com.example.rex.ota30.R.id.textView;
public class Search extends AppCompatActivity implements LocationListener {
private FirebaseDatabase db;
private DatabaseReference sref, lref;
private TextView searchun, searchlo, searchla;
private String un, la, lo;
private LocationManager lm;
private LocationListener ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
db = FirebaseDatabase.getInstance();
sref = db.getReference("users");
lref = db.getReference("userslocation");
searchun = (TextView) findViewById(R.id.sun);
Intent i = this.getIntent();
un = i.getStringExtra("username");
searchun.setText(un);
searchlo = (TextView) findViewById(R.id.slo);
searchla = (TextView) findViewById(R.id.sla);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
}
@Override
public void onLocationChanged(Location location) {
la = String.valueOf(location.getLatitude());
searchla.setText(la);
lo = String.valueOf(location.getLongitude());
searchlo.setText(lo);
lref.child(un).child("latitude").setValue(la);
lref.child(un).child("longitude").setValue(lo);
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
Here's the sample of the getting location.
回答1:
OnLocationChanged is only called when the location has changed.
So the location is displayed in the Textview only when the send button is pressed.
If you want to display the location from the beginning, try this
protected void onCreate(Bundle savedInstanceState) {
...
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
...
// add code
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
la = String.valueOf(location.getLatitude());
searchla.setText(la);
lo = String.valueOf(location.getLongitude());
searchlo.setText(lo);
}
回答2:
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener,
View.OnClickListener {
private static final String TAG = "MapsActivity";
private GoogleMap mMap;
private double longitude;
private double latitude;
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
// .compassEnabled(true);
// Add a marker in Sydney and move the camera
LatLng india = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
private void moveMap() {
/**
* Creating the latlng object to store lat, long coordinates
* adding marker to map
* move the camera with animation
*/
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onClick(View view) {
Log.v(TAG,"view click event");
}
@Override
public void onConnected(@Nullable Bundle bundle) {
getCurrentLocation();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onMapLongClick(LatLng latLng) {
// mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
}
@Override
public void onMarkerDragStart(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDrag(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDragEnd(Marker marker) {
// getting the Co-ordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//move to current position
moveMap();
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
return true;
}
}
来源:https://stackoverflow.com/questions/46293122/current-location-not-auto-display-to-the-textview