I would like to know how to get the speed of a vehicle using your phone while seated in the vehicle using gps. I have read that the accelerometer is not very accurate. Another thing is; will GPS be accessible while seated in a vehicle. Won't it have the same effect as while you are in a building?
Here is some code I have tried but I have used the NETWORK PROVIDER instead.I will appreciate the help. Thanks...
package com.example.speedtest;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
LocationManager locManager;
LocationListener li;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
li=new speed();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, li);
}
class speed implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
Float thespeed=loc.getSpeed();
Toast.makeText(MainActivity.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
}
for more information onCalculate Speed from GPS Location Change in Android Mobile Device view this link
Mainly there are two ways to calculate the speed from mobile phone.
Calculate speed from Accelerometer
Calculate speed from GPS Technology
Unlike Accelerometer from GPS Technology if you're going to calculate speed you must enable data connection and GPS connection.
In here we are going to calculate speed using GPS connection.
In this method we using how frequency the GPS Location points are changing during single time period. Then if we have the real distance between the geo locations points we can get the speed. Because we have the distance and the time.
Speed = distance/time
But getting the distance between two location points is not very easy. Because the world is a goal in shape the distance between two geo points is different from place to place and angle to angle. So we have to use “Haversine Algorithm”
First we have to give permission for Get Location data in Manifest file
Make the GUI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtCurrentSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="000.0 miles/hour"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox android:id="#+id/chkMetricUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Use metric units?"/>
Then make an interface to get the speed
package com.isuru.speedometer;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public interface IBaseGpsListener extends LocationListener, GpsStatus.Listener {
public void onLocationChanged(Location location);
public void onProviderDisabled(String provider);
public void onProviderEnabled(String provider);
public void onStatusChanged(String provider, int status, Bundle extras);
public void onGpsStatusChanged(int event);
}
Implement the logic to get the speed using the GPS Location
import android.location.Location;
public class CLocation extends Location {
private boolean bUseMetricUnits = false;
public CLocation(Location location)
{
this(location, true);
}
public CLocation(Location location, boolean bUseMetricUnits) {
// TODO Auto-generated constructor stub
super(location);
this.bUseMetricUnits = bUseMetricUnits;
}
public boolean getUseMetricUnits()
{
return this.bUseMetricUnits;
}
public void setUseMetricunits(boolean bUseMetricUntis)
{
this.bUseMetricUnits = bUseMetricUntis;
}
#Override
public float distanceTo(Location dest) {
// TODO Auto-generated method stub
float nDistance = super.distanceTo(dest);
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nDistance = nDistance * 3.28083989501312f;
}
return nDistance;
}
#Override
public float getAccuracy() {
// TODO Auto-generated method stub
float nAccuracy = super.getAccuracy();
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nAccuracy = nAccuracy * 3.28083989501312f;
}
return nAccuracy;
}
#Override
public double getAltitude() {
// TODO Auto-generated method stub
double nAltitude = super.getAltitude();
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nAltitude = nAltitude * 3.28083989501312d;
}
return nAltitude;
}
#Override
public float getSpeed() {
// TODO Auto-generated method stub
float nSpeed = super.getSpeed() * 3.6f;
if(!this.getUseMetricUnits())
{
//Convert meters/second to miles/hour
nSpeed = nSpeed * 2.2369362920544f/3.6f;
}
return nSpeed;
}
}
Combine logic to GUI
import java.util.Formatter;
import java.util.Locale;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity implements IBaseGpsListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.updateSpeed(null);
CheckBox chkUseMetricUntis = (CheckBox) this.findViewById(R.id.chkMetricUnits);
chkUseMetricUntis.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
MainActivity.this.updateSpeed(null);
}
});
}
public void finish()
{
super.finish();
System.exit(0);
}
private void updateSpeed(CLocation location) {
// TODO Auto-generated method stub
float nCurrentSpeed = 0;
if(location != null)
{
location.setUseMetricunits(this.useMetricUnits());
nCurrentSpeed = location.getSpeed();
}
Formatter fmt = new Formatter(new StringBuilder());
fmt.format(Locale.US, "%5.1f", nCurrentSpeed);
String strCurrentSpeed = fmt.toString();
strCurrentSpeed = strCurrentSpeed.replace(' ', '0');
String strUnits = "miles/hour";
if(this.useMetricUnits())
{
strUnits = "meters/second";
}
TextView txtCurrentSpeed = (TextView) this.findViewById(R.id.txtCurrentSpeed);
txtCurrentSpeed.setText(strCurrentSpeed + " " + strUnits);
}
private boolean useMetricUnits() {
// TODO Auto-generated method stub
CheckBox chkUseMetricUnits = (CheckBox) this.findViewById(R.id.chkMetricUnits);
return chkUseMetricUnits.isChecked();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
CLocation myLocation = new CLocation(location, this.useMetricUnits());
this.updateSpeed(myLocation);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onGpsStatusChanged(int event) {
// TODO Auto-generated method stub
}
}
If you want to convert Meters/Second to kmph-1 then you need to multipl the Meters/Second answer from 3.6
Speed from kmph-1 = 3.6 * (Speed from ms-1)
GPS works fine in a vehicle. The NETWORK_PROVIDER setting might not be accurate enough to get a reliable speed, and the locations from the NETWORK_PROVIDER may not even contain a speed. You can check that with location.hasSpeed() (location.getSpeed() will always return 0).
If you find that location.getSpeed() isn't accurate enough, or it is unstable (i.e. fluctuates drastically) then you can calculate speed yourself by taking the average distance between a few GPS locations and divide by the time elapsed.
public class MainActivity extends Activity implements LocationListener {
add implements LocationListener next to Activity
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
LocationManager.GPS_PROVIDER, 0, 0, The first zero stands for minTime and the second one for minDistance in which you update your values. Zero means basically instant updates which can be bad for battery life, so you may want to adjust it.
#Override
public void onLocationChanged(Location location) {
if (location==null){
// if you can't get speed because reasons :)
yourTextView.setText("00 km/h");
}
else{
//int speed=(int) ((location.getSpeed()) is the standard which returns meters per second. In this example i converted it to kilometers per hour
int speed=(int) ((location.getSpeed()*3600)/1000);
yourTextView.setText(speed+" km/h");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
}
Don't forget the Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
We can use location.getSpeed();
try {
// Get the location manager
double lat;
double lon;
double speed = 0;
LocationManager locationManager = (LocationManager)
getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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 = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
speed =location.getSpeed();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
mTxt_lat.setText("" + lat);
mTxt_speed.setText("" + speed);
}catch (Exception ex){
ex.printStackTrace();
}
Related
This app will beep whenever the user's location changes. The problem is, the app will continue monitoring the user's location even after they have left the app and it is in the background.
How do I stop the location listener, once the app goes into the background?
I think I have to add something to the OnPause(), but I can't make it work.
package com.example.locationbeeper;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements LocationListener {
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set up location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 200, 5, this); // time in miliseconds, distance in meters (Distance drains battry life) originally set to 20000 and 0
}
#Override
public void onLocationChanged(Location location) {
// beep when location changed
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
tg.startTone(ToneGenerator.TONE_PROP_BEEP);
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onPause(){
super.onPause();
locationManager = null;
}
}
Based on your requirement, you can add below lines either in onPause() or onStop() callback method of your activity.
if(locationManager !=null)
locationManager.removeUpdates(this);
Use LocationManager.removeUpdates to stop receiving updates from LocationManager when Activity is stop:
#Override
public void onStop(){
super.onStop();
if(locationManager !=null)
locationManager.removeUpdates(this);
}
I'm working on an Android app which gets your current location upon clicking a button, and then prints it if you click another button.
Now, I've got all of the code done, yet I'm stuck into how to retrieve the info of the longitude and latitude to print it, because I earn it on another function.
I'll post my code below to explain what I mean in a clearer manner:
package com.example.geolocation;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener, LocationListener {
private LocationManager locationManager;
public String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(this);
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(this);
Button show = (Button)findViewById(R.id.show);
show.setOnClickListener(this);
TextView location = (TextView)findViewById(R.id.location);
TextView providers = (TextView)findViewById(R.id.providers);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
//funcions boto start
case R.id.start:
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
500, //distancia (meters)
this);
//mostrar provider
TextView location = (TextView)findViewById(R.id.location);
location.setText("Provider: " + provider);
break;
//funcio boto stop
case R.id.stop:
locationManager.removeUpdates(this);
break;
//funcio boto show
case R.id.show:
Location locations = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
1000, //distancia (meters)
this);
//show long & lat
TextView providers = (TextView)findViewById(R.id.providers);
providers.setText("Latitude & longitude: " + ""); //com traslladar valor loc aqui?
break;
}
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
loc.toString();
}
#Override
public void onProviderDisabled(String np) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String p) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
The segment where I get the desired info is this one:
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
loc.toString();
}
As you can see, I turn the information into a String.
Now, my problem is: how do I call this info in the main function to print it? In this segment:
//funcio boto show
case R.id.show:
Location locations = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(
provider,
10000, //temps em ms (10s)
1000, //distancia (meters)
this);
//show long & lat
TextView providers = (TextView)findViewById(R.id.providers);
providers.setText("Latitude & longitude: " + ""); //com traslladar valor loc aqui?
break;
what you have to do is the following :
1st - declare a String to store your lattitude and longitude :
private String lattitude , longitude;
2nd - in your get onLocationChanged do the following :
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
int lat = (int) (loc.getLatitude());
int lng = (int) (loc.getLongitude());
lattitude = "lattitude = "+ lat ;
longitude = "longitude = "+ lng;
}
3rd - use the lattitude and longitude to print them in any place you want .
Hope that helps .
hello i'm pretty new to android..
i'm making an application which needs exact(approx 50m accuracy acceptable) user location..
i'm using locationmanager and locationlistener..
whenever i start the application i need user location returned. problem is that onlocationchanged method in locationlistener returns the latitude longitude only when they change..
how do i get user location ?
locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loclist_netwk);
this is how i'm calling the class where i've implemented locationlistener.
`
package com.example.gpsmanager;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MyLocationListener extends Activity implements LocationListener
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylocation_layout);
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
loc.getLatitude();
loc.getLongitude();
String text="my current location is"+"lat: "+loc.getLatitude()+"long: "+loc.getLongitude();
//TextView text1=(TextView) findViewById(R.id.textView1);
//text1.setText(text+"");
Toast.makeText(MyLocationListener.this, text, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
String text="GPS Provider not availabe";
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
String text="GPS Provider availabe";
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
`
pllzz plzz help guys... thankss..
For user location you can use Reverse Geocoding
For it u have to send only lat,long.
Code is below:-
public String getAddress(double lat, double lng,Context mContext) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng,1);
String add="";
for(int i=0;i<addresses.size();i++){
Address obj = addresses.get(i);
//String = obj.getAddressLine(i);
add = add+obj.getAddressLine(i)+","+obj.getLocality()+","+obj.getAdminArea()+","+obj.getCountryName();
Log.v("IGA", "\n"+"Address " + add);
}
return add;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
Note -- Solved
This is the function which is setting the center in my map , with GPS locations i want more highest precise level and zoom level , what changes i have to make ?
package cc.co.ratan.www;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class Collegemap extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.collegemap);
MapView view =(MapView) findViewById(R.id.themap);
view.setBuiltInZoomControls(true);
final MapController control = view.getController();
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new LocationListener() {
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
control.setCenter(new GeoPoint((int)arg0.getLatitude(), (int)arg0.getLongitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listner);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
this is my code after i edited . (looked and made changes from your blog )
package cc.co.ratan.www;
import java.text.DecimalFormat;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class Collegemap extends MapActivity implements LocationListener{
private String provider;
GeoPoint myLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//String provider;
setContentView(R.layout.collegemap);
MapView mview =(MapView) findViewById(R.id.themap);
mview.setBuiltInZoomControls(true);
Criteria criteria = new Criteria();
final MapController control = mview.getController();
LocationManager manager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
Location location = manager.getLastKnownLocation(manager.NETWORK_PROVIDER);
if (location != null)
plotLocation(location);
else
manager.requestLocationUpdates(
manager.NETWORK_PROVIDER, 500L, 250.0f, (LocationListener) this);
provider = manager.getBestProvider(criteria, false);
LocationListener listner = new LocationListener() {
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(Collegemap.this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(Collegemap.this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
control.setCenter(new GeoPoint((int)arg0.getLatitude(), (int)arg0.getLongitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listner);
;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
double roundTwoDecimals(double d){
DecimalFormat twoDForm = new DecimalFormat("#.######");
return Double.valueOf(twoDForm.format(d));
}
public void plotLocation(Location location) {
GeoPoint point = new GeoPoint(
(int) (roundTwoDecimals(location.getLatitude()) * 1E6),
(int) (roundTwoDecimals(location.getLongitude()) * 1E6));
myLocation = point;
MapView mview =(MapView) findViewById(R.id.themap);
mview.getController().animateTo(point);
mview.getController().setCenter(point);
zoomToMyLocation();}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
private void zoomToMyLocation() {
if (myLocation != null) {
MapView mview =(MapView) findViewById(R.id.themap);
mview.getController().setZoom(18);
mview.getController().animateTo(myLocation);
}
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}}
#Ratan -- I think some code is missing from your activity...
Check below code plotmylocation will center map to gps location & zoomtomylocation will zoom map to that location you can add any zoom level there instead of 18 but I think 20 will be max value.
public class MapDragActivity extends MapActivity implements LocationListener{
String pinadd="";
private MapView map=null;
private LocationManager locationManager;
GeoPoint myLocation;
/** Called when the activity is first created. */
#SuppressWarnings("static-access")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maplayout);
map=(MapView)findViewById(R.id.map);
map.setBuiltInZoomControls(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
plotLocation(location);
else
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 500L, 250.0f, this);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null)
plotLocation(location);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#SuppressWarnings("static-access")
#Override
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);
}
#Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onDestroy(){
locationManager.removeUpdates(this);
super.onDestroy();
}
public void plotLocation(Location location) {
GeoPoint point = new GeoPoint(
(int) (roundTwoDecimals(location.getLatitude()) * 1E6),
(int) (roundTwoDecimals(location.getLongitude()) * 1E6));
myLocation = point;
map.getController().animateTo(point);
map.getController().setCenter(point);
zoomToMyLocation();
}
private void zoomToMyLocation() {
if (myLocation != null) {
map.getController().setZoom(18);
map.getController().animateTo(myLocation);
}
}
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
I am looking for the optimized way to get user's location and I found the sample example here, which was answered by Mr. Fedor on on Jun 30 '10
I did the same way as he explained in his code, the only difference is that I am using the gotLocation callback method of abstract class result. In this method I am tring to show the Provider name as a msg using Toast.makeText. When I run this code, nothing get displayed on my emulator and after few seconds it show the message "Application has stopped unexpectedly android emulator". I increase the time, which was set in the timer1.schedule method, but no luck.
I am just stating development in android platform, so I don't have enough knowledge about the same, so can anybody help me to resolve this issue.
Below is my code
file Name: UserLocation.java
package com.ideafarms.android.mylocation;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class UserLocation{
Timer timer1;
LocationManager locMgr;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerNetwork);
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerGps);
}
};
public boolean getLocation(Context context, LocationResult result){
// Use LocationResult callback class to pass location value from UserLocation to User code
locationResult = result;
if(locMgr == null){
locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Handle exception if provider is not permitted
try{
gps_enabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
// don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled){
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
return true;
}
class GetLastLocation extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
locMgr.removeUpdates(locationListenerGps);
locMgr.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled){
gps_loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled){
net_loc=locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
// if there are both values use the latest one
if(gps_loc!=null && net_loc!= null){
if(gps_loc.getTime()>net_loc.getTime()){
locationResult.gotLocation(gps_loc);
}else{
locationResult.gotLocation(net_loc);
}
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
and
package com.ideafarms.android.mylocation;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.ideafarms.android.mylocation.UserLocation.LocationResult;
public class MyLocation extends Activity {
/** Called when the activity is first created. */
TextView myLoc ;
public LocationResult locResult = new LocationResult(){
#Override
*public void gotLocation(Location location) {
// TODO Auto-generated method stub
Toast msg = Toast.makeText(MyLocation.this, location.getProvider(), Toast.LENGTH_LONG);
//msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}*
};
boolean loc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
UserLocation usrLocation = new UserLocation();
myLoc = (TextView)findViewById(R.id.myLocation);
loc = usrLocation.getLocation(this, locResult);
}
}
I have marked the code in italic where I am having problem.
Thanks
Take a look here: http://developer.android.com/guide/developing/tools/emulator.html
You need to emulate an gps device in order to get location data from the emulator.