Experimenting with Android location services - android

I'm trying to use a sample code (http://www.hrupin.com/2011/04/android-gps-using-how-to-get-current-location-example) that I found to see how the location services work. My code compiles, however it seems that I can't get past one part in particular when the app runs. Below is the code I am using
package com.example.gpstest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
progress = (ProgressBar) findViewById(R.id.progressBar1);
progress.setVisibility(View.GONE);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(this);
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#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 onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEUTRAL){
editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
}else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
}
The app will not get past this if statement (I keep getting the msg "Sorry, location is not d..." that it kicks out) :
if (!gps_enabled & !network_enabled)
The original statement read:
if (!gps_enabled && !network_enabled)
however I couldn't get this to compile (eclipse didn't like all the 'amps'), so I took my best guess at what it was trying to do, but I think I butchered its meaning.
if anyone could help me get this code to work, or point me in the direction of a different example so I can play with it, that would be very helpful.
edit I did add all the appropriate permmisions: access coarse location, access fine location, and Internet (just for laughs, as I'm almost positive this code doesn't need Internet)
edit changed the '&' in my code to '&&'
edit added permissions manualy and everything is now working (I orignaly used the GUI option):
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

I copied your code into a new project, added the two required permissions to the manifest, and used the && replacement Jim suggested. It works just fine on my phone.
I think you must have the permissions set incorrectly in the manifest or, probably, your phone doesn't have its GPS properly enabled for your app.
The documentation for isProviderEnabled states that "If the user has enabled this provider in the Settings menu, true is returned otherwise false is returned." The only exception I know of is that the method always returns false if your app doesn't declare the needed permissions.
If you're on an emulator or if you have your GPS disabled, that would explain it. Try getting your current location in an existing location-based application, like Google Maps.

It looks like you probably need a short-circuiting AND operator &&, rather than the
bitwise AND operator & there.

Related

My App cannot send request to get Location

I am writhing now simple weather program. I use weather Api and must send location of phone to get weather data. As you understand I don't need precise location, so no need for GPS, noneed for ACCESS_FINE_LOCATION. What I need is - to get my location from NETWORK_PROVIDER. But here starts the problem.
At first I tried to use LocationManager and LocationListener. I enabled my WiFi and location in phone settings. Important thing that I want my application work indoor, so that no need for walking to change coordinates and LocationManager will respond. At first I check last known location.
Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER);
Actually, often it does not work. So I get null as location. Especiall when you turn off location in smartphone settings and after a few minutes turn it on.
OKAY, you don't have lastKnownLocation, then lets get it us. I use requestLocationUpdates() to get current location:
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
Now the magic begins... Sometime (one time in several hours OR several times in a minute) the requestLocationUpdates() works. But most of time it does not react. After many searches in internet I found Google Api, in particular FusedLocationProviderClient class. But again same story happens. But now I could understand that requestLocationUpdates() is not called.
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
I decided to put a button to see does it sends any requestLocationUpdates, but when I click button I have error.
587-673/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
To Summarize, my app simply dont send requestLocationUpdates. And I need just approximate location of my device to get city name, so no need for GPS. Please help me to solve this problem. Thanks.
You can use this class to get Current or Last Known Location if current location is currently not available.
initialize activity in your Manifest.xml
inside application tag
<activity android:name=".LocationFinder"></activity>
start this activity by calling
startActivity(new Intent(getApplicationContext(), LocationFinder.class));
finish();
Now, you can get Location in any other activity by just calling -> LocationFinder.finalAddress
Location and Internet permissions required
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
LocationFinder.java
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;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
#SuppressLint("MissingPermission")
public class LocationFinder extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private String provider;
public static String finalAddress;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoc();
}
public void getLoc() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
location = getLastKnownLocation();
}
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(this, "Location not available...", Toast.LENGTH_SHORT).show();
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
#SuppressLint("MissingPermission")
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex()+1;
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
finalAddress = builder.toString(); //This is the complete address.
} catch (IOException | NullPointerException e) {
// Handle IOException
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
After getting complete address you can use split method to get country name etc

Incorrect Location updates with wifi/mobile network but not with GPS

Following is the coding i got from some one else work. I am trying to implement bit of his work with necessary changes in my app. The problem here is that it is not returning the proper address when the GET ADDRESS button is clicked. Besides, it works only with the wifi/mobile network but not with the GPS. Meanwhile, i wonder how to make auto-posting of data to sever when the call is making to a contact. Thank you!
package com.yang.address;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AddressActivity extends Activity {
/** Called when the activity is first created. */
Double lat, lon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLocation = (Button)findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = location.getLatitude();
lon = location.getLongitude();
TextView tv = (TextView) findViewById(R.id.txtLoc);
tv.setText("Your Location is:" + lat + "--" + lon);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
});
Button btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
postData(lat, lon);
}
});
Button btnAdd = (Button)findViewById(R.id.btnAddress);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.txtAddress);
tv.setText(GetAddress(lat, lon));
}
});
}
public void postData(Double lat2, Double lon2) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet htget = new HttpGet("http://myappurl.com/Home/Book/"+lat2+"/"+lon2);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(htget);
String resp = response.getStatusLine().toString();
Toast.makeText(this, resp, 5000).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "Error", 5000).show();
} catch (IOException e) {
Toast.makeText(this, "Error", 5000).show();
}
}
public String GetAddress(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
}
Looks like you've made some progress since your last question.
First off, the LocationManager system on androids is Listening Service in that you register it as a listener and allow the OS to notify when updates are made. This means you should have the code you put in your OnClick method run before you need it. Your best option is to have the OnCreate method of your Activity register the listener as the Activity starts and use the onLocationChanged callback as a way to store the new Location on a class variable.
private Location lastKnownLocation;
private TextView tv;
public void onCreate(Bundle savedInstanceState) {
//....
setupLocationServices();
//....
tv = (TextView) findViewById(R.id.txtLoc);
Button btnLocation = (Button)findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
updateLocation();
}
});
//....
}
private void setupLocationServices() {
//....
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lastKnownLocation = location;
updateLocation();
}
....
}
private void updateLocation() {
double lat = lastKnownLocation.getLatitude();
double lat = lastKnownLocation.getLongitude();
tv.setText("Your Location is:" + lat + "--" + lon);
}
As for your reasoning as to why it doesn't work with GPS it is because you never register the GPS listener. Where you have this line:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You would need to substitude in this value:
LocationManager.GPS_PROVIDER
Again, as I recommended before I really suggest taking the time to fully understand the Android Developer documentation
As for your other problem regarding listening to the state of incoming calls you should start off by checking the TelephonyManager documentation here. Specifically look for the use of ACTION_PHONE_STATE_CHANGED and its extras for incoming calls. For outgoing calls google the use of ACTION_NEW_OUTGOING_CALL Intents.

automatically update location without restart the application

i am building a simple android application which require me to auto update the location. the auto update location will not only update when resuming the application but must auto update whenever the application is on. this application looks like the same with GPS system that were put inside the car. it get the exact location and always update the current location. i want to the same thing in here. i am building this application on android 2.2.
here is my code:
package com.example.map;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.widget.Toast;
public class MapActivity extends Activity implements LocationListener{
private TextView latituteField, longitudeField, accuracyField, altitudeField, bearingField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
accuracyField = (TextView) findViewById(R.id.textView1);
altitudeField = (TextView) findViewById(R.id.textView2);
bearingField = (TextView) findViewById(R.id.textView4);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
int acc = (int) (location.getAccuracy());
int alt = (int) (location.getAltitude());
int bearing = (int) (location.getBearing());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
accuracyField.setText(String.valueOf(acc));
altitudeField.setText(String.valueOf(alt));
bearingField.setText(String.valueOf(bearing));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
this code it only update the location value when im resuming the application (i quit the application then go back to the application). the location will be updated at the viewtext.
i also tried to do while. like this.
if(location != null){
do{
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}while(location != null);
}
else{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
im adding this to the manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
however, this code makes the application crash in a real phone. is there anyway to get this done?
*note: i tested all this application in my real phone and trying to achieve the current location. the textview suppose to change whenever it gets the new value of the location without pausing or quitting the application.
You have to put your location code inside an ScheduledExecutor Service:
http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
That one repeats actualization function in the background for example every 30 seconds or whatever time you specify.
Example:
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
// This schedule a task to run every 10 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
//add your code you would like to be executed every 10 seconds.
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 10, TimeUnit.SECONDS);
you also might have to add a permission for coarse location.

onLocationChanged() never called

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.

How can i find my current location if i am indoor? ANDROID

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.

Categories

Resources