Getting current location in Android - android

I know it is a common question and has been answered a number of times... But I am looking for an answer to a specific problem.
I have written a method which is required to return current lat/long as string. The code goes like this:
public class LibraryProvider {
public String basicMethod(String string) {
String text = string;
LocationManager locationManager;
String provider;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
text = "Provider " + provider + " has been selected.";
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
text = text + "\n" + "lat: " + String.valueOf(lat);
text = text + "\n" + "lng: " + String.valueOf(lng);
} else {
text = "Location not available";
}
return text;
}
}
However, the android studio is not allowing this.get System Service:
cannot resolve Method getSystemService(java.lang.String)
I am new to android and not clear about context and intents... I think the problem has something to do with it.
(edited)
the code i was using to load the above class is as under
private final class ServiceHandler extends android.os.Handler {
public ServiceHandler(Looper looper){
super(looper);
}
public void handleMessage(Message msg){
dynamicClassLoader();
}
String text;
private void dynamicClassLoader(){
final String apkFile =Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/apkFile.apk";
String className = "com.va.android.level2.lib.LibraryProvider";
final File optimisedDexOutputPath = getDir("outdex", 0);
DexClassLoader classLoader = new DexClassLoader(apkFile,optimisedDexOutputPath.getAbsolutePath(),null,getClassLoader());
try{
Class loadedClass = classLoader.loadClass(className);
// LibraryInterface lib = (LibraryInterface) loadedClass.newInstance();
// lib.basicMethod("hello");
Object obj =(Object)loadedClass.newInstance();
Method method = loadedClass.getMethod("basicMethod", String.class);
text = (String) method.invoke(obj,"added method");
showOutput(text);
} catch (Exception e){
e.printStackTrace();
}
}
private void showOutput(final String str){
mServiceHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this,str, Toast.LENGTH_LONG).show();
}
});
}
}
earlier it was working, but now it is raising some exception at loadedClass.newInstance(); .....i think i need to pass the context ...but how??

Try get Activity Context reference in custom class constructor and use it ;
public class LibraryProvider {
private Context context;
public LibraryProvider(Context context){
this.context=context;
}
}
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

You need a Context to call getSystemService(...).
Actually you are calling it from "this" that is not a class that has a Context.

try this
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("DEBUG",location.toString());
double lat = location.getLatitude();
double lon = location.getLongitude();
}
};

try this
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
see this link on how to get current location in Android

Related

how do I update the latitude and longitude to the textview in android main activity having dependency injection with dagger 2

I am beginner in android. I am now learning dagger 2 dependency injection. I am coding an app which update the latitude and longitude to the textview screen. I don't know, how i would I update the location coordinates to the textview screen as i did the coding of onLocationChanged in the module class and I am injecting the class to the main activity.
I did the coding of getting the location update in LocationManager class.
I can show the updated coordinates using toast, but not able to change textview, is there any way to do this ?
The code in the main activity
public class MainActivity extends AppCompatActivity {
#Inject
LocationManager locationManager;
#InjectView(R.id.textView2)
TextView addressLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
MyApplication.inject(this);
locationManager.GetLocation();
}
}
I like to update the addressLocation textview with the coordinates that i am getting from LocationListener.
package com.test.xyz.daggersample1.service.impl;
public class LocationManager {
Geocoder geocoder;
List<Address> addresses;
private double lattitude = 0;
private double longitude = 0;
private Context context;
public LocationManager(Context context) {
this.context = context;
}
public String GetLocation() {
final String[] address = new String[1];
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return "";
}
geocoder = new Geocoder(context, Locale.getDefault());
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
lattitude = location.getLatitude();
// dialog.dismiss();
Toast.makeText(context, "Got the Longitude as " + longitude + " Lattitude as " + lattitude, Toast.LENGTH_SHORT).show();
**I like to pass these location values to the textview in the main activity**
try {
addresses = geocoder.getFromLocation(lattitude, longitude, 1);
address[0] = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "Got the Longitude as " + longitude + " Lattitude as " + lattitude, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(i);
}
};
locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 2000, 10, listener);
return address[0];
}
}
My project folder

How to get the data from the BroadcastReceiver to another class BroadcastReceiver

I am using the BroadcastReceiver in my application ,here i am receiving the current location and place in this class.hence i am getting the current location,hence my question is how to send this location string from this class to another class .i have to load this string data in the listview in another class so how can do this please help thanks in advance. My code is
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
MyTrip trip_method;
double latitude, longitude;
Context context;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
protected LocationManager locationManager;
Location location;
#Override
public void onReceive(Context context, Intent intent) {
trip_method = new MyTrip();
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Find_location();
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
public void Find_location() {
// Location nwLocation;
try {
location = getLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("nwLocation-------" + location);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println("latitude-------" + latitude + "longitude-----" + longitude);
Toast.makeText(
context,
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
// To display the current address in the UI
(new GetAddressTask()).execute(location);
} else {
trip_method.showSettingsAlert("NETWORK");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
/* *//**//*
* Following is a subclass of AsyncTask which has been used to get
* address corresponding to the given latitude & longitude.
*//**//**/
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
/* public GetAddressTask(Context context) {
super();
mContext = context;
}*/
/* *//**//*
* When the task finishes, onPostExecute() displays the address.
*//**//**/
#Override
protected void onPostExecute(String address) {
// Display the current address in the UI
Toast.makeText(context.getApplicationContext(),
"address---" + address,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Location... params) {
String Address = null;
String Location = null;
Geocoder geocoder;
List<android.location.Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2);
Location = addresses.get(0).getAddressLine(2);
System.out.println("Location----" + Location);
//This "Location" value i have to send to another activity
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the text
return Address;
/* } else {
return "No address found";
}*/
}
}// AsyncTask class
}
Use this in your code as appropriate:
In your First class:
Intent intent = new Intent(this, another_activity.class);
intent.putExtra("Location", Location.toString);
startService(intent)
In your Second class:
String Location = getActivity().getIntent.getStringExtra("Location")
Now you have passed string from one class to another. Use the Location variable where you need it.

is it posible to use locationManager in a non-activity class

am trying to create a class that will be used in acquiring the users Location. this class will be utilized by an IntentService in the background.
is there a way to do this without extending Activity or FragmentActivity
in my class.
the code so far looks like below.
import android.app.IntentService;
import android.content.Context;
import static android.content.Context.LOCATION_SERVICE;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class LocateMe {
// set loc Listener
LocationManager locationManager;
String update_locid, provider;
double mLon, mLat;
Float accuracy;
int count = 0;
Criteria criteria;
Context context;
IntentService is;
onLocationGot mCallback;
public LocateMe(onLocationGot ints){
is = (IntentService) ints;
// This makes sure that the container service has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (onLocationGot) ints;
} catch (ClassCastException e) {
throw new ClassCastException(ints.toString()
+ " must implement LocateMe.onLocationGot");
}
}
private LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Getting latitude of the current myLocation
double latitude = location.getLatitude();
// Getting longitude of the current myLocation
double longitude = location.getLongitude();
// getting accuracy
accuracy = location.getAccuracy();
// Setting latitude and longitude to be used in the TextView
mLat = latitude;
mLon = longitude;
if (count > 5) {
locationManager.removeUpdates(mLocationListener);
}
count++;
mCallback.foundLocation(mLat, mLon, accuracy);
// finish();
}
public void onProviderDisabled(String provider) {// more work required here
// str = provider;
}
public void onProviderEnabled(String provider) {
// str = provider;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
provider = locationManager.getBestProvider(criteria, true);
}
};
// #Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
public void getLocation() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(is.getBaseContext( ));
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
// int requestCode = 10;
// Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
// dialog.show();
} else {
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) is.getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
//criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location or on editing saved location
if (provider != null) {
requestLocation(locationManager, provider);
} else {
//start wifi, gps, or tell user to do so
}
}
}
public void requestLocation(LocationManager locationManager, String provider) {
if (provider != null) {
locationManager.requestLocationUpdates(provider, 1000, 0, mLocationListener);
} else {
//tell user what has happened
}
}
public interface onLocationGot {
public void foundLocation(double lat, double lon, Float accuracy);
}
}
I suspect that your question is if you can get LocationService in non-activity class.
If so, then read below.
To access system services you need to call this method. Activity extends Context, so it's able to get system services. IntentService also extends Context, so you can use your constructor param to get location service.

onLocationChanged never gets called Emulator

package com.ecsmon.android.core;
import static com.ecsmon.android.constants.Constants.log;
import java.io.IOException;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
#SuppressLint("NewApi")
public class GPSManager {
private double currentLatitude = 0d;
private double currentLongitude = 0d;
private static Context mCtx;
private Location lastLocationBestProvider = null;
private LocationManager mLocationManager;
private GPSListenerImpl mGPSListener;
private com.ecsmon.android.core.LocationListener mOutListener;
private boolean enabled = false;
private GPSListenerImpl mNETListener;
public GPSManager(Context ctx, com.ecsmon.android.core.LocationListener locationListener) {
mCtx = ctx;
mLocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
mOutListener = locationListener;
}
/**
* Start location updates
*/
public void start() {
log("#### Started tracking");
lastLocationBestProvider = getLastLocationFromBestProvider();
if (lastLocationBestProvider != null) {
currentLatitude = lastLocationBestProvider.getLatitude();
currentLongitude = lastLocationBestProvider.getLongitude();
log("lat" + currentLatitude + " long " + currentLongitude);
} else {
log("last loaction is null");
}
// mGPSListener = new GPSListenerImpl("GPS");
mNETListener = new GPSListenerImpl("NET");
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 1, mNETListener);
// mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, mGPSListener);
}
private class GPSListenerImpl implements LocationListener {
private String name = "";
public GPSListenerImpl(String name) {
log("listener created" + name);
this.name = name;
}
public void onLocationChanged(Location loc) {
log("######### LOCATION CHANGED CALLED!!!!!!!!!!!!!!!!! ##############");
if (loc != null) {
log("######### location changed " + loc.getAccuracy());
currentLatitude = loc.getLatitude();
currentLongitude = loc.getLongitude();
mOutListener.update(currentLongitude, currentLatitude);
} else {
log("location is null");
}
}
public void onProviderDisabled(String provider) {
log("provider disabled > " + name);
}
public void onProviderEnabled(String provider) {
log("provider enabled > " + name);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
log("status changed");
}
}
/**
* Return last location saved in phone or null
*
* #return Location
*/
public Location getLastLocationFromBestProvider() {
if (!enabled) {
return null;
}
try {
LocationManager lm = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
String strLocationProvider = lm.getBestProvider(criteria, true);
Location location = lm.getLastKnownLocation(strLocationProvider);
if (location != null) {
return location;
}
return null;
} catch (Exception e) {
log(e.getMessage());
return null;
}
}
/**
* Returns human readable address from longitude and latitude
*
* #param latitude
* #param longitude
* #return
*/
public String getAddress(Double latitude, Double longitude) {
if (!enabled) {
return null;
}
String m = "";
try {
if (!Geocoder.isPresent()) {
return null;
}
Geocoder geo = new Geocoder(mCtx);
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
return null;
} else {
if (addresses.size() > 0) {
m = addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() + ", "
+ addresses.get(0).getCountryName();
}
}
} catch (IOException ie) {
log("No connection.");
return null;
} catch (Exception e) {
log("Can't read adress from this cordinates : lat = " + latitude + " long " + longitude); //
return null;
}
return m;
}
/**
* Removes all location updates
*/
public void stop() {
try {
mLocationManager.removeUpdates(mGPSListener);
mLocationManager.removeUpdates(mNETListener);
} catch (Exception e) {
}
}
}
This is my main class for fetching current location and onLocationChanged never gets called. Im testing on emulator, and sending mock longitude and latitude via Emulator Control. Please Help this is driving me mad :(
Stefan was right. You need to do 2 things.
Grant access to mock location. As of now this needs to be specified in a special manifest file under src/debug/AndroidManifest.xml. Create that xml and add this permission to it:
uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
Make sure your location manager is hooked on to the GPS provider and not the network provider. That information can be found here:
http://developer.android.com/guide/topics/location/strategies.html#MockData
You can change the GPS location values of emulator using Emulator control. By doing this (onLocationChanged method will work) you can test your application in Emulator
Problem is on emulator it wont work, but on real device it found my location in sec
In my case, the problem was for the update frecuency of the accelerometer and magnetic_field sensors. Only changed "SensorManager.SENSOR_DELAY_FASTEST" or SensorManager.SENSOR_DELAY_GAME" to "SensorManager.SENSOR_DELAY_NORMAL" and it´s worked correctly.
Curiously, the frecuency of the GPS sensor can be "SensorManager.SENSOR_DELAY_FASTEST" and don´t have any problem.

DummyLocationProvider issue

I'm trying to get the latitude and longitude and below is class which does that...
But i get android runtime exception at
Location l = locMgr.getLastKnownLocation(bestProvider);
and at longt = Double.toString(loc.getLongitude());
Also provider is always shown as DummyLocationProvider even on the phone
public class Util implements LocationListener {
public static LocationManager locMgr;
private static List<String> providers;
private static String bestProvider;
private Context context;
public static String lat;
public static String longt;
public Util(Context context) {
this.context = context;
if(locMgr == null) //Get LocationManager
locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void getLocations() {
//List All providers
providers = locMgr.getAllProviders();
//Get criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get best provider
bestProvider = locMgr.getBestProvider(criteria, false);
printProvider(bestProvider);
//Get Last known location
Location l = locMgr.getLastKnownLocation(bestProvider);
if(l==null)
System.out.println("im null");
printLocation(l);
}
private void printLocation(Location loc) {
if(loc == null) { //means there is no recent location
getNewLocation();
}else
lat = Double.toString(loc.getLatitude());
longt = Double.toString(loc.getLongitude());
System.out.println("cached " + lat + " " + longt);
}
private void printProvider(String provider) {
System.out.println(provider);
LocationProvider info = locMgr.getProvider(provider);
System.out.println("provider= " + info.toString() + "\n\n");
}
private boolean getNewLocation() {
if(locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //This is executed since it can get locations faster than gps (is executed only if use wireless networks for locations is selected)
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
return true;
}else if(locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //This is exceuted if n/w locations is turned off & gps is turned on
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return true;
}else { //executed when gps & location by network is turned off..
return false;
}
}
Please modify your code, it may help you..
Location l = context.locMgr.getLastKnownLocation(bestProvider);

Categories

Resources