I am writing a code that brings current location but it is not giving me the location because it never calls onLocationChanged() .Is there any way to find the location.
mobileLocation is coming 0 for this case, so the execution goes to the else block.
My code is
public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;
public FindLocation(Context ctx){
locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
locListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
} else {
System.out.println("in find location 4");
Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();
}
}
}
i run my app on real device .
i use network instead of GPS and onLocationChanged is called:
locMan.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null);
Do you never get a location or only as you write in your comment "sometimes it gets location but not at the time of click."?
Might be that your code is faster than LocationManager, which might not yet have called onLocationChanged(). Change your code in order to get the last known location, or wait until your locListener was called:
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1, locListener);
mobileLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {
LocationManager.NETWORK_PROVIDER need network, but it is real, not precise; if you want to use LocationManager.GPS_PROVIDER, the situation must be outdoor instead of indoor, because GPS location need satellite, if you are in any building, the satellite cannot find you!
I thing you forgot permission
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
OR
Declare Proper Class like
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location arg0) {
latitude = arg0.getLatitude();
longitude = arg0.getLongitude();
}
}
Directly after locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener), add the following code:
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locListener);
EDIT: corrected the code thanks to the comment by #Fabian Streitel.
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import org.json.JSONObject;
import java.util.List;
public class AndroidLocationServices extends Service {
PowerManager.WakeLock wakeLock;
String MODULE="AndroidLocationServices",TAG="";
private LocationManager locationManager;
double getLattitude=0,getLogitude=0;
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
public AndroidLocationServices() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
preferences=getSharedPreferences(GlobalConfig.PREF_NAME, MODE_PRIVATE);
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
// Toast.makeText(getApplicationContext(), "Service Created",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("Google", "Service Started");
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500, 0, listener);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
}
public LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
location.setAccuracy(100);
if (location == null)
return;
getLattitude=location.getLatitude();
getLogitude=location.getLongitude();
Log.e("latitude", getLattitude + "");
Log.e("longitude", getLogitude + "");
}
#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 onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// wakeLock.release();
}
}
Manifest:
<service android:name=".services.AndroidLocationServices"/>
Start Service before use:
startService(new Intent(this, AndroidLocationServices.class));
In my case the app was not asking for permissions. Although I have added the permissions in menifest file. So I was not able to allow my app to access the location.
As a fix, I manually went to: Settings->Permissions->Your location and enabled the location permission for my under-development app. And that fixed my problem.
I assume that this issue is only when the app is installed through Android Studio. I hope it will not occur when the app is installed from Google Play.
Related
package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
double latitude;
double longitude;
private LocationManager lm;
ArrayList<Point> pt;
Point p;
private Context context;
private Location loc;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(){
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
loc = location;
Toast.makeText(getApplicationContext(), "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude(), Toast.LENGTH_LONG).show();
updateList();
}
#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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
this.loc = null;
pt = new ArrayList<Point>();
p = new Point();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
So, in this code, my intention is to save a list of Points in an ArrayList of Points that will be use later. But all the points (latitude and longitude) have the same value, once i have the first value, all the others values are the same, its seems like onLocationChanged is never called.
Can someone help me?
You have a global point p that you're overwriting every call to updateList. Since you aren't creating a new point ever, this overwrites the old values. That means every element in your list will always have the most recent values, rather than the value at that time.
Also, why are you using class variables everywhere rather than passing parameters to functions? I have a feeling you don't understand Java or references very well.
Edit:
Here's what your code should look like, with locals used correctly:
package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
private LocationManager lm;
ArrayList<Point> pt;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(Location loc){
Point p = new Point();
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Lat: " + location.getLatitude() + "Long: " + location.getLongitude(), Toast.LENGTH_LONG).show();
updateList(location);
}
#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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
pt = new ArrayList<Point>();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I am trying to get the location from the GPS but not able to get it. this is because the location is accessed by the Network provider.
If I am commenting all the code of network provider then the GPS location returns null.
I have tried so much, but unable to resolve this.
If anybody can help then it will be great help for me.
I am using this link for the reference..
https://stackoverflow.com/a/3145655/1395259
Here is my code:
MainActivity.java
package com.example.locationsimple;
import com.example.locationsimple.MyLocation.LocationResult;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
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;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
LocationResult locationResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textViewLocation);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationResult = new LocationResult(){
#Override
public void gotLocation(Location location) {
while(true)
{
Log.i("Log", "Inside while loop ");
if(location != null)
{
Log.i("Log", "Here the location is not null");
if(location.getLatitude() !=0.0 || location.getLongitude() != 0.0)
{
if(location.getAccuracy() < 100)
{
Log.i("Log", "Inside while loop BREAKS");
try
{
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, ""+loc, Toast.LENGTH_LONG).show();
textView.setText(loc);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
}
else
{
Log.i("Log", "no Accuracy");
Log.i("Log", "latti"+location.getLatitude()+" Longi "+location.getLongitude()+" Accur "+location.getAccuracy()+location.getProvider());
break;
}
}
}
else
{
Log.i("Log", "Here got the location is null");
break;
}
}
//textView.setText(location.getLatitude()+"::"+location.getLongitude()+"::"+location.getAccuracy()+" Provider "+location.getProvider());
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(MainActivity.this, locationResult);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyLocation.java
package com.example.locationsimple;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
Context mContext;
public boolean getLocation(Context context, LocationResult result)
{
mContext = context;
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
lm.getBestProvider(criteria, true);*/
//exceptions will be thrown if provider is not permitted.
try
{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex)
{
ex.printStackTrace();
}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled || !network_enabled)
{
showSettingsAlert();
return false;
}
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("GPS Is Not Enabled");
// Setting Dialog Message
alertDialog.setMessage("Please Enabled Wireless Network And GPS");
// On pressing Settings button
alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// Showing Alert Message
alertDialog.show();
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
// lm.removeUpdates(locationListenerNetwork);
Location net_loc=null;
Location gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.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);
}
}
Thanks..
You can use the below service for getting gps.just invoke this service at the begining.
public class MyService extends Service {
LocationManager locationManager;
#Override
public void onCreate() {
//
// TODO Auto-generated method stub
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
/** Criteria for selecting best provider */
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
/** Passing criteria and select only enabled provider */
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
/** calls the Location Listner */
locationManager.requestLocationUpdates(provider, 500, 0,locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location)
{
System.out.println("+++++++++++++++++++SASI+++++++++++++++++++++++++++++++++++++++++");
String latLongString, addressString = null;
double lat = 0, lng = 0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
//latLongString = "Lat:" + lat + "\nLong: " + lng;
/** Getting Address */
} else {
latLongString = "No location found";
addressString = "No location found";
}
//System.out.println("###########" + addressString + lat + lng);
SearchDeals.latPoint=location.getLatitude();
SearchDeals.lngPoint=location.getLongitude();
Deals_route.sourcelati=location.getLatitude();
Deals_route.sourcelong=location.getLongitude();
}
#Override
public void onDestroy() {
super.onDestroy();
//
//Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(locationListener);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
//Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I've just tested the above code on my device and everything is working smoothly, not sure what is the problem at your end.
Important notes:
Please make sure you have the permission to access GPS location in your manifest file
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
The code may not work properly on the emulator , better test on actual device. if you don't have access to one , please checkout the DMMS Emulator Control to generate location data
Edit:
you need to commit out the Location data related to Network Provider.
and Also remove the textView.setText from your LocationResult object because textView is null. so the fixes:
getLocation(Location location) {
.........
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime() +" "+location.getProvider();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, loc, Toast.LENGTH_LONG).show();
}
and comment out the network code from your MyLocation class
// if(network_enabled)
// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
I want to find my current location if GPS is not avaible and there is no wireless?
I think i need to do some calculation or there is some codes that it can do it for me.?
Thx.
I wrote like that code but it can not find current location when i am indoor.
package com.anil.bestlocation;
import java.util.List;
import android.app.Activity;
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.widget.TextView;
public class showBestLocation extends Activity implements LocationListener{
/** Called when the activity is first created. */
private static final String[] S = { "Out of Service",
"Temporarily Out of Service",
"Available" };
private TextView output;
private LocationManager locationManager;
private String bestProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
output = (TextView) findViewById(R.id.txtLoc);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//list all providers
List<String> providers = locationManager.getAllProviders();
for(String provider : providers){
printProvider(provider);
}
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
output.append("\n\nBEST PROVIDER:\n");
printProvider(bestProvider);
output.append("Location.. (initialized with the last known location):");
Location location = locationManager.getLastKnownLocation(bestProvider);
printLocation(location);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
printLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
output.append("\n\nSProvider Disabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
output.append("\n\nProvider Enabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
output.append("\n\nProvider Status Changed: " + provider +
", Status= " + S[status]);
}
private void printProvider(String provider){
LocationProvider info = locationManager.getProvider(provider);
output.append(info.toString() + "\n\n");
}
private void printLocation(Location location){
if(location == null){
output.append("\nLocation UNKNOWN\n\n");
}
else{
output.append("\n\nLatitude: " + location.getLatitude() + "\nLongitude: " + location.getLongitude());
}
}
}
http://developer.android.com/guide/topics/location/obtaining-user-location.html
More Specifically:
http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestPerformance
Indoors you can use the NetworkProvider to get location. This method uses a combination of mobile cell tower information and nearby wifi base station information to approximate your location.
The way it does this is by scanning the area for wifi base stations and collecting the mobile operator's cell tower information from nearby cell towers. It then sends all this data to a server and asks the server to estimate your location.
If you have no Internet access (ie: no wifi connection and no mobile data connection) then you will not get any location information. There isn't anything you can do about this. That's just the way it works.
You will need some sort of input to retrieve the location. Your calculations will have to be based on something. Depending on your phones hardware, you could try and use bluetooth, NFC or try and detects some frequency that is emitted by a transmitter (That will have to be placed at the location). I hope this helps you.
I want to find out current location when the Application is running in background
I Have below code for finding current location in background running services. But its not working.
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MyService extends Service {
private static LocationManager mlocManager;
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "start My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
//Location newloc= new Location();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
Toast.makeText(this, "hiiiits created", Toast.LENGTH_LONG).show();
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onlocationchnage");
loc.getLatitude();
loc.getLongitude();
String Text ="My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}/* End of Class MyLocationListener */
}
I think you need Current Latitude and Longitude values using GPS..
follow this link.. Click link
I already tried it and test it in android mobile phone.. Its working.
Note :
emulator we are not get the Curent GPS location.. You must and should install your application in phone..
First you ON the GPS in mobile phone after try it, it will work.
have a nice day.
I have small service implementing LocationListener. I tested it manually with my application and it works properly.
I wrote also a test case for the service.
I used setTestProviderLocation expecting that service will receive location update.
However, it does not happen.
Does anybody know what's a problem? I'd like to emphasize that the same service works in real application.
Test case is added below
package com.gkatz.android.mtg.test;
import java.util.List;
import com.gkatz.android.mtg.LocationService;
import com.gkatz.android.mtg.LocationService.LocationBinder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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.os.IBinder;
import android.os.SystemClock;
import android.test.ServiceTestCase;
public class LocationServiceTest extends ServiceTestCase<LocationService> implements LocationListener{
public LocationServiceTest() {
super(LocationService.class);
// TODO Auto-generated constructor stub
}
#Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
}
public void testBinding(){
IBinder locationBinder;
locationBinder = getServiceBinder();
assertNotNull(locationBinder);
}
public void testStart(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
startService(locationIntent);
}
public void testNoStart(){
LocationService locationService = getService();
assertNull(locationService);
}
public void testLocationUpdate() throws InterruptedException{
LocationBinder locationBinder;
LocationService locationService;
Context context = getContext();
LocationManager lm = getLocationManager();
context.registerReceiver(locationReceiver,
new IntentFilter("android.mtg.custom.intent.action.GPS_LOCATION"));
locationBinder = (LocationBinder)getServiceBinder();
assertNotNull(locationBinder);
locationService = getService();
assertNotNull(locationService);
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLongitude(4.890935);
loc.setLatitude(52.373801);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
SystemClock.sleep(3000);
loc.setLongitude(35.2276757);
loc.setLatitude(31.7765488);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
synchronized (this) {
this.wait(2000);
}
Location lastLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Last known longitude: " + Double.toString(lastLoc.getLongitude()) +
"Last known latitude: " + Double.toString(lastLoc.getLatitude()));
assertEquals(35.2276757, locationService.getLongitude());
assertEquals(31.7765488, locationService.getLatitude());
context.unregisterReceiver(locationReceiver);
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
}
private BroadcastReceiver locationReceiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
assertTrue(intent.getAction().equals("android.mtg.custom.intent.action.GPS_LOCATION"));
System.out.println("Action received: " + intent.getAction());
this.notify();
}
};
private IBinder getServiceBinder(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
return bindService(locationIntent);
}
private LocationManager getLocationManager(){
LocationManager lm = (LocationManager)
getContext().getSystemService(Context.LOCATION_SERVICE);
lm.addTestProvider(LocationManager.GPS_PROVIDER,
true, true, true, true, true, true, true,
Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE, null, System.currentTimeMillis());
lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
return lm;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
System.out.println("LocationServiceTest, onLocationChanged, lon:" +
Double.toString(location.getLongitude()) + ", lat:" +
Double.toString(location.getLatitude()));
}
#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
}
}
Try with
// Register the listener with the Location Manager to receive location updates
lm.requestLocationUpdates("YOUR PROVIDER", 0, 0, YOUR_LOCATION_LISTENER);
Found at Location guide of Android Developers