I would like to create an app that can calculate distance between 2 location, the first is find with GPS,while the second is set by me. The app doesn't open, and the error is in the
line 61: distance = location.distanceTo(locationSede);
Help me!
package com.example.prova.mapapplicationprove;
import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements LocationListener {
private float distance;
private float[] distfloat = new float[1];
private final LatLng POINT = new LatLng(0, 0); //longitudine e latitudine
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
LatLng sede = new LatLng(45.012447, 7.621013);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(POINT, 1));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
map.addMarker(new MarkerOptions().position(sede).title("Soluzioni"));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
if(provider != null & !provider.equals(""))
{
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(provider, 2000, 1, this);
Location locationSede = new Location("Sede");
locationSede.setLatitude(45.012447);
locationSede.setLongitude(7.621013);
distance = location.distanceTo(locationSede); //LINE NUMBER 61
// location.distanceBetween(sede.latitude,sede.longitude,location.getLatitude(),location.getLongitude(),distfloat);
if(location!=null)
{
onLocationChanged(location);
}
else{
Toast.makeText(getApplicationContext(),"Location not found, GPS disabled.",Toast.LENGTH_LONG ).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Provider is null.",Toast.LENGTH_LONG).show();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this,"Latitude: " + location.getLatitude() + "\nLongitude: " + location.getLongitude(),Toast.LENGTH_LONG ).show();
TextView textView2 = (TextView) findViewById(R.id.textview2);
TextView textView3 = (TextView) findViewById(R.id.textview3);
TextView textView4 = (TextView) findViewById(R.id.textview4);
String distanza = String.valueOf(distance);
//String distanza = String.valueOf(distfloat[0]);
textView2.setText("Latitude="+location.getLatitude());
textView3.setText("Longitude="+ location.getLongitude());
textView4.setText("Distance="+ distanza);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prova.mapapplicationprove">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Per usare il GPS -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.prova.mapapplicationprove.MainActivity" />
</activity>
</application>
</manifest>
I think you should put
distance = location.distanceTo(locationSede); //LINE NUMBER 61
into method
#Override
public void onLocationChanged(Location location) {
}
It'll look like
#Override
public void onLocationChanged(Location location) {
if (location != null){
Location locationSede = new Location("Sede");
locationSede.setLatitude(45.012447);
locationSede.setLongitude(7.621013);
int distance = location.distanceTo(locationSede);
}
}
If you want to calculate distance between 2 points then you can use to Location.distanceBetween( A.Latitude, A.Longitude, B.Latitude, B.Longitude, result);
See below code how to impliment in your code
float[] result = new float[1];
Location.distanceBetween(location.getLatitude(), location.getLongitude(), locationSede.getLatitude(), locationSede.getLongitude(), result);
Log.e("TAG Result",""+result); //Here result is your distance
double km = result * 0.001;
Log.e("TAG Result",""+km); //Here distance in kilometer
Here when you want to distance in kilometer that time total distance with multiply 0.001 as like distancein_km=total_dis*001
I resolve my problem, the error is caused by the provider: I use locationManager.allProvider(); and in this way it works.
Thanks anyway
Related
I am trying to write an app that gets the current location and displays the latitude and longitude realtime. However, when I run this app, the gps doesn't seem to search for a location and try to get a fix. I don't know why this is happening. Have I missed something out? If I open the maps app the location immediately gets a fix. But in my app the gps is not searching for one, or atleast, in the notification bar, it is not showing anything like 'searching for gps' which is usually shown by the maps app.
My main activity:
package com.example.android.location1;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, LocationListener{
private final String LOG_TAG = "TestApp";
private TextView txtOutput;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private static final int REQUEST_PERMISSION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).build();
txtOutput = (TextView) findViewById(R.id.txtOutput);
}
#Override
protected void onStart(){
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop(){
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000).setMaxWaitTime(2000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i){
Log.i(LOG_TAG, "GoogleApiClient connection has been suspended.");
}
#Override
public void onLocationChanged(Location location){
Log.i(LOG_TAG, location.toString());
txtOutput.setText(String.valueOf(location.getLatitude()) + ", " + String.valueOf(location.getLongitude()));
}
}
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.location1">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
<uses-feature android:name="android.hardware.location.network"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have tested this on android 6 and 7. Doesn't work in either of them. Any help would be appreciated.
Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Then register the locationupdates and attach it to the listener that you already have implementet
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3, 1, locationListener);
Read about the requestlocationsUpdates method on how often etc you what your location.
https://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates
i'm trying to build a GPS app with Android Studio. It's working okay on the first run but whenever i close the app and open it again or go to desktop and back into it, as i have figured until now, my LocationListener doesn't get called anymore.
Practically what happens is that it doesn't display my location as intended the second time. No error no anything.
Here's my code, thanks in advance if you can help. I've been searching a lot :(
package com.madnzz.googlemapsstuff;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
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.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.sql.Time;
import java.util.Random;
import com.google.android.gms.appindexing.AndroidAppUri;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import static com.madnzz.googlemapsstuff.R.id.activity_chooser_view_content;
import static com.madnzz.googlemapsstuff.R.id.repositionButton;
/*
TODO: Replace retard user icon with improved one
*IMPLEMENT the way the user is facing. http://android-coding.blogspot.ro/2012/03/create-our-android-compass.html
*
TODO: implement GPS routes https://www.youtube.com/watch?v=CCZPUeY94MU or http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
*REPLACE consumed path with cookie crumb graphic
TODO: save path and able to share with others.
TODO later: Battery efficiency https://developer.android.com/guide/topics/location/strategies.html
*/
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
////////////////////////////////////////////////////////////////////////////////////
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListening();
}
}
}
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
Random random=new Random();
GroundOverlayOptions[] c00kieCrumb=new GroundOverlayOptions[200];
int i=0;
///////////////////////////////////////////////////////////////////////////////
public void addCrumb(LatLng userLocation){
int randomCrumbBearing=random.nextInt(36)*10;
c00kieCrumb[i] = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.frateeeee))
.position(userLocation, 3,3).bearing(randomCrumbBearing);
c00kieCrumb[i].isVisible();
i++;
for (int j = 0; j < i; j++) {
mMap.addGroundOverlay(c00kieCrumb[j]);
}
}//adds new cookie crumb to user location
public void putCrumbConditions(LatLng userLocation){
for (int j = 0; j < i; j++) {
mMap.addGroundOverlay(c00kieCrumb[j]);
}
if (i == 0) {
addCrumb(userLocation);
} else {
if (Math.abs((c00kieCrumb[i - 1].getLocation().latitude - userLocation.latitude)) > 0.00003
|| Math.abs(c00kieCrumb[i - 1].getLocation().longitude - userLocation.longitude) > 0.00003) {
addCrumb(userLocation);
}
}
}//adds a new cookie crumb to the user location 4
// IF THE USER IS 0.00003 UNITS AWAY FROM LAST CRUMB PLACED
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("ZiciCinci created shit", "Am ajuns aici");
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);
}
#Override
protected void onDestroy(Bundle savedInstanceState){
super.onDestroy();
}
LatLng [] locationCalibrator,savedUserLocation;
LatLng userLocation,previousUserLocation;
Boolean gpsCalibrationInProgress,tooClose,firstIteration,mapCenteredOnUserPosition,cameraFollowUserPosition;
int locationIteration=0,savedUserLocationPos;
ImageButton repositionButton;
#Override
public void onMapReady(GoogleMap googleMap) {
Log.i("ZiciPatru map is ready","Am ajuns aici");
mMap = googleMap;
c00kieCrumb[0] = new GroundOverlayOptions();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationCalibrator = new LatLng[100];
gpsCalibrationInProgress = true;
locationIteration = 0;
i = 0;
savedUserLocation = new LatLng[3];
savedUserLocationPos = 0;
tooClose = true;
firstIteration = true;
mapCenteredOnUserPosition = true;
cameraFollowUserPosition = true;
previousUserLocation = new LatLng(0, 0);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Zici3 gps calibration","Am ajuns aici");
userLocation = new LatLng(location.getLatitude(), location.getLongitude());
if (!gpsCalibrationInProgress) {
if (Math.abs(previousUserLocation.latitude - userLocation.latitude) > 0.000003 ||
Math.abs(previousUserLocation.latitude - userLocation.longitude) > 0.000003) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)).rotation(0));
if (firstIteration) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
firstIteration = false;
}
LatLng userDestination = new LatLng(44.4187432, 26.1556372);
mMap.addMarker(new MarkerOptions().position(userDestination).title("COOOOKIESTUFF").icon(BitmapDescriptorFactory.fromResource(R.drawable.c00ki3_marker_128x128)));
putCrumbConditions(userLocation);
}
} else {
Toast.makeText(getApplicationContext(), "Calibrating gps, please stand still", Toast.LENGTH_SHORT).show();
locationCalibrator[locationIteration] = userLocation;
locationIteration++;
if (locationIteration >= 2) {
if (Math.abs(locationCalibrator[locationIteration - 1].latitude - userLocation.latitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 1].longitude - userLocation.longitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 2].latitude - userLocation.latitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 2].latitude - userLocation.latitude) < 0.0001) {
gpsCalibrationInProgress = false;
}
}
}
previousUserLocation = userLocation;
repositionButton = (ImageButton) findViewById(R.id.repositionButton);
repositionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("rarara","q");
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
repositionButton.setBackgroundResource(R.drawable.location_centered);
mapCenteredOnUserPosition = true;
cameraFollowUserPosition = true;
}
});
if (mapCenteredOnUserPosition) {
mMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int reason) {
if (reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) {
repositionButton.setBackgroundResource(R.drawable.location_not_centered);
mapCenteredOnUserPosition = false;
cameraFollowUserPosition = false;
}
}
});
}
if (cameraFollowUserPosition) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
repositionButton.setBackgroundResource(R.drawable.location_centered);
}
LocationServices.FusedLocationApi.removeLocationUpdates(GoogleApiClient,this)
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getApplicationContext(), "Please activate your location", Toast.LENGTH_SHORT);
}
};
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
if (!tooClose) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)));
}
tooClose = false;
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
My android manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.madnzz.googlemapsstuff">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:exported="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
android:roundIcon="#mipmap/ic_launcher_round"
-->
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" >
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.madnzz.googlemapsstuff.MapsActivity"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ImageButton
android:id="#+id/repositionButton"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="40dp"
android:layout_marginEnd="30dp"/>
<!--android:onClick="repositionMap"-->
android:background="#drawable/location_not_centered" />
</RelativeLayout>
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
if (!tooClose) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)));
}
tooClose = false;
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The problematic part of the your code(and also scenario),
You did make location request if lastKnownLocationis null. After receiving new location one time(onLocationChanged), getLastKnownLocationwill not return null, and location request will not be called for later starts(except boot)
As a result, onLocationChanged called only one time.
getLastKnownLocation will give you the latest location obtained from given provider.It's possible to get null. You just used GPS_PROVIDER but could also try NETWORK_PROVIDER too
mGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
With this you can increase chance of getting a location. If both of them null then make location request provider(s) (sorry there is no magic, you must, like others do)
I cant get latitude and longitude in lollipop.It works fine in other versions like gingerbread and kitkat and maximum sdk is 22. I have given
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.project2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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>
Java code .
package com.example.project2;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener {
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 10 * 1; // 10 sec
protected LocationManager locationManager;
protected Context context;
protected boolean gps_enabled, network_enabled;
TextView txtLat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.t1);
locationManager = (LocationManager)getSystemService(Context.Location_Service);
// getting GPS status
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVID ER);
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} else if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
};
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.t1);
txtLat.setText("Latitude:"+ location.getLatitude() + ", Longitude:"
+ location.getLongitude());
}
#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");
}
}
I did it in Eclipse Juno.My main intention is to get location and send to another mobile which i provided.But first I am not getting any location.
Please go through the following links.
Location issue with lollipop
Retrieve current location
It may help you. If not, let me know.
Avoid using this old method and look at Making Your App Location-Aware
When I press the button btnlocation it should go to the Mapsactivity
but it is giving me the error:
java.lang.NoClassDefFoundError
I also added MapsActivity in manifest as usual .. .but why this error? I need the solution.Can any one help me please...
package com.mamun.tasktest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class FragmentB extends Fragment implements OnClickListener {
private Button btnLocation;
private LocationManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b, null, false);
btnLocation = (Button) view.findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(this);
manager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("GPS is currently disabled");
builder.setMessage("Please enable GPS for better view of your location.\nWould you like to change these settings now?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity();
}
});
builder.create().show();
}
return view;
}
#Override
public void onClick(View v) {
if(isMapAvailalble()){
/////////////////////////////
/*
// */
//////////////////////////
Intent in = new Intent(getActivity(),MapsActivity.class);
startActivity(in);
}
}
/*Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false);
sendBroadcast(intent);*/
//if googleplayservis or play store is not available/updated or user recoverable problem occured.
public boolean isMapAvailalble()
{
// to test if there is no googleplayservise
//int resultcode=ConnectionResult.SERVICE_MISSING;
int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS==resultcode)
{
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(resultcode))
{
Dialog d = GooglePlayServicesUtil.getErrorDialog(resultcode, getActivity(), 1);
d.show();
}
else
{
Toast.makeText(getActivity()," Google Map API is not supported in your device",Toast.LENGTH_LONG).show();
}
return false;
}
/*public void turnGPSOn()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
((Context) this.ctx).sendBroadcast(intent);
#SuppressWarnings("deprecation")
String provider = Settings.Secure.getString(((Context) ctx).getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
((Context) this.ctx).sendBroadcast(poke);
}*/
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mamun.tasktest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-library android:name="com.google.android.maps"/>
<permission
android:name="com.mamun.tasktest.permission.MAPS_RECEIVE"
android:protectionLevel="signature" >
</permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mamun.tasktest.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCgGng3iaqbTxJ3B_lYemZBEqXOonUtFEI" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name="MapsActivity"></activity>
</application>
</manifest>
MapsActivity
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapActivity;
public class MapsActivity<GeoPoint, OverlayItem> extends MapActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
MapView mapView;
com.google.android.maps.GeoPoint p;
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public void draw(Canvas canvas, com.google.android.maps.MapView mapView,
boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
}
#Override
public boolean onTouchEvent(MotionEvent e,
com.google.android.maps.MapView mapView) {
// TODO Auto-generated method stub
if (e.getAction() == 1) {
com.google.android.maps.GeoPoint p = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
Toast.makeText(
getBaseContext(),
"Lat: " + p.getLatitudeE6() / 1E6 + ", Lon: "
+ p.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT)
.show();
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Add Activity into your manifest.xml because you need to give all path if your Activity located into different package.
<activity
android:name="com.mamun.tasktest.MapsActivity"
android:label="MapActivity" >
</activity>
And/or is your Activity belong to the same package then add simply
<activity android:name=".MapsActivity"></activity>
For more information go to:http://developer.android.com/guide/topics/manifest/manifest-intro.html
This is incorrect:
<activity android:name="MapsActivity"></activity>
You need to give full or relative path like this:
<activity android:name="com.mamun.tasktest.MapsActivity"></activity>
or
<activity android:name=".MapsActivity"></activity>
Replace your this tag in manifest
<activity android:name="MapsActivity"></activity>
by :
<activity android:name=".MapsActivity"></activity>
you should specify your full package name while declaring your activity into manifets.
See this link for reference:-
Add a new activity to the AndroidManifest?
You just forget to place a DOt (.) before MapsActivity. So, without that Dot (.) your class path looks like...
com.mamun.tasktestMapsActivity.java
But, it should be as....
com.mamun.tasktest.MapsActivity.java
Now, change this line of your Manifest...
<activity android:name="MapsActivity"></activity>
to...
<activity android:name=".MapsActivity"></activity>
I got the solution....The line "" should be inside application not inside directly on manifest.Like as below....
I'd like to get Geo location by using GPS provider. So my code will be like this
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
LocationManager lm;
TextView textLatitude, textLongitude;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLatitude = (TextView)findViewById(R.id.textLatitude);
textLongitude = (TextView)findViewById(R.id.textLongitude);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
/* Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);*/
}
public void onResume() {
super.onResume();
setup();
}
public void onStart() {
super.onStart();
boolean gpsEnabled, networkEnabled;
gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d("LocationService","GPS Status: "+gpsEnabled);
if(!gpsEnabled) {
networkEnabled =
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!networkEnabled) {
Intent intent =
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
}
public void onStop() {
super.onStop();
lm.removeUpdates(listener);
}
public void setup() {
lm.removeUpdates(listener);
String latitude = "Unknown";
String longitude = "Unknown";
Location gpsLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, "GPS not supported");
if(gpsLocation != null) {
Log.d("Location Service","GET FROM GPS");
latitude = String.format("%.7f", gpsLocation.getLatitude());
longitude = String.format("%.7f", gpsLocation.getLongitude());
}
textLatitude.setText(latitude);
textLongitude.setText(longitude);
}
public Location requestUpdatesFromProvider(final String provider
, String error) {
Location location = null;
if (lm.isProviderEnabled(provider)) {
lm.requestLocationUpdates(provider, 0, 0, listener);
Log.d("LocationService","Requesting...");
location = lm.getLastKnownLocation(provider);
//Log.d("LocationSerivce", "Geo :"+location.getLatitude());
} else {
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
return location;
}
public LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location) {
textLatitude.setText(String.format("%.7f", location.getLatitude()));
textLongitude.setText(String.format("%.7f",location.getLongitude()));
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider
, int status, Bundle extras) { }
};
}
The result is ... IT DOESN'T WORK. What have I done wrong?
I've also added permission to manifest file already.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name
="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationservice.MainActivity"
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>
</manifest>
I search a lot from Internet and I got that it'll work if I combine with Network provider and I have to use internet to get my location. This is not what I want.
I want to get Location from GPS only because I'll use for offline application.
Could you give me any great suggestion. I'll thanks a lot