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.
Related
I have to find the location of user such that , that even when I close the app it continues in the background. The code working fine and it's displaying correct locations but when I click "Start Service" It crashes. I can't find the mistake:
GPS TRACKING CLASS
package com.malay.gpsservice;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class GPSTracService extends Service implements LocationListener {
// DECLARE ALL THE VARIABLES
Location location = null; // location
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled=false;
String msg = "CAUTION! If kept open, can consume lots of battery";
// FOR FOREGROUND_ID
int FORE_ID = 1335;
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("NewApi")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent noty_intent = new Intent(this,
com.malay.gpsservice.MainActivity.class);
noty_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, noty_intent,
0);
Notification n = new Notification.Builder(this)
.setContentTitle("GPS Serice is running...")
.setContentText(msg).setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).setAutoCancel(true).setOngoing(true)
.build();
startForeground(FORE_ID, n);
try {
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// First get location from Network Provider
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network","Network");
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if (!isGPSEnabled) {
} else {
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(this,
"Location Listener on GPS started...",
Toast.LENGTH_SHORT).show();
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception ex) {
Toast.makeText(this,
"Some Error occur while starting Location Listener",
Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
return (START_STICKY);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (locationManager != null) {
locationManager.removeUpdates((LocationListener) this);
locationManager = null;
}
stopForeground(true);
Toast.makeText(this, "Location Listener on GPS Stopped...",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
here is the main activity:
package com.malay.gpsservice;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener{
Context mcontext=this;
boolean isGpsEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
protected LocationManager locManager;
Location loc=null;
double latitude;
double longitude;
double accuracy;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE=20;
private static final long MIN_TIME_BETWEEN_UPDATE=1000*60;
double latitudet;
double longitudet;
double accuracyt;
TextView tview;
TextView tlat;
TextView tlon;
TextView tacc;
String lat;
String lon;
String acc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loc=getLocation();
tview = (TextView) findViewById(R.id.textView1);
try {
getGPSLoc();
} catch (Exception e) {
e.printStackTrace();
}
}
#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;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
//Refresh Button
if (item.getItemId() == R.id.ref) {
getLocation();
getGPSLoc();
}
return super.onMenuItemSelected(featureId, item);
}
public void getGPSLoc() {
if (latitude != 0.0 && longitude != 0.0) {
tview.setText("Location Fixed");
} else {
tview.setText("Waiting for Location...");
}
if (canGetLocation) {
latitudet=(double)Math.round(latitude*1000000)/1000000;
tlat = (TextView) findViewById(R.id.lat);
lat = Double.toString(latitudet);
tlat.setText(lat);
longitudet=(double)Math.round(longitude*1000000)/1000000;
tlon = (TextView) findViewById(R.id.lon);
lon = Double.toString(longitudet);
tlon.setText(lon);
accuracyt=(double)Math.round(accuracy*100)/100;
tacc = (TextView) findViewById(R.id.acc);
acc = Double.toString(accuracyt);
tacc.setText(acc);
}
}
public Location getLocation(){
try{
locManager=(LocationManager)mcontext.getSystemService(LOCATION_SERVICE);
isGpsEnabled=locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGpsEnabled || isNetworkEnabled){
this.canGetLocation=true;
// First get location from Network Provider
if(isNetworkEnabled){
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, (LocationListener) this);
Log.d("Network","Network");
if(locManager!=null){
loc=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
accuracy=loc.getAccuracy();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if(isGpsEnabled){
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, (LocationListener) this);
Log.d("GPS Enabled","GPS Enabled");
if(locManager!=null){
loc=locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
accuracy=loc.getAccuracy();
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
return loc;
}
public void startServ(View vw){
Intent gps=new Intent(this,GPSTracService.class);
this.startService(gps);
}
public void stopServ(View vw){
Intent gps=new Intent(this,GPSTracService.class);
this.stopService(gps);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
Menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.malay.gpsservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.malay.gpsservice.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>
<service android:name=".GPSTracService" />
</application>
</manifest>
Logcat
Use getApplicationContext() instead of this in service.
Changed below line.
Intent noty_intent = new Intent(getApplicationContext(), com.malay.gpsservice.MainActivity.class);
.
.
Notification n = new Notification.Builder(getApplicationContext())
instead of
Intent noty_intent = new Intent(this, com.malay.gpsservice.MainActivity.class);
Note : must declare service in menifest.xml if it missing.
Update :
Use below code for Notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setStyle(new NotificationCompat.BigTextStyle().bigText("App Name"))
.setContentText("App Name");
startForeground(1, mBuilder.build());
Use android.support.v7 library and set Target Version 21
I researched for this Nullpointer Exception. After googling i found most of them were due to null references to the UI elements. But mine does not have any. I just can't get the reason for the null pointer. I directly tested it on my android phone running 2.3.7. And yes, i added the permissions in the manifest file.
package com.GodTM.projectshoppers;
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.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class HomeActivity extends Activity {
private ImageButton get;
private ImageView quit,settings;
private LocationManager locMan;
public LocationListener LocLis;
public Location currLoc;
private double[] passloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
get=(ImageButton)findViewById(R.id.homeGetButton);
settings = (ImageView)findViewById(R.id.homeSettingsButton);
quit = (ImageView)findViewById(R.id.homeExitButton);
Criteria crit=new Criteria();
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LocLis = 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
if(location != null){
currLoc.setLatitude(location.getLatitude());
currLoc.setLongitude(location.getLongitude());
}
}
};
//Criteria crit = new Criteria();
if(currLoc !=null){
passloc[0] = currLoc.getLatitude();
passloc[1] = currLoc.getLongitude();
Toast.makeText(getApplicationContext(), "Lat:" + currLoc.getLatitude() + "\nLong:" + currLoc.getLongitude(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Not Available", Toast.LENGTH_SHORT).show();
}
get.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(currLoc!=null){
Intent i = new Intent(HomeActivity.this, Screen2.class);
i.putExtra("Loc", passloc);
startActivity(i);
}
else{
Toast.makeText(getApplicationContext(), "Location Not Available", Toast.LENGTH_SHORT).show();
}
}
});
settings.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent j = new Intent(this, screen4.class);
// startActivity(j);
}
});
quit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onResume(){
super.onResume();
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER , 0, 0, LocLis);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
currLoc is never initalized. Since location and currLoc are both Location you can change
if(location != null){
currLoc.setLatitude(location.getLatitude());
currLoc.setLongitude(location.getLongitude());
}
with
currLoc = location;
You didn't initialize passLoc. And you call getLastKnownLocation without saving the location itself.
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();
}
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;
}
}