Latitude and Longitude return Null - android

I'm trying to print the latitude and longitude, along with accelerometer readings in my application. However, when I try to use the latitude and longitude from my GPS class in my Main Activity class, it always returns null. Can someone tell me what I'm doing wrong? I've tried countless different approaches (the internet is full of them), but none seem to resolve my problem. Thanks.
MainActivity.java
package com.explorer.extractor;
//import packages
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity implements SensorEventListener,OnClickListener {
GPSTracker gps;
Button button1;
Button button2;
private SensorManager mSensorManager;
Sensor accelerometer;
private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "newgps.txt"; //file where data is written
//layout variables
TableLayout t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize sensor manager
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//initialize accelerometer
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
t1 = (TableLayout) findViewById(R.id.main_table);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy){}
/**onResume() registers the accelerometer for listening
* to the events
*/
/*
protected void onResume(){
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
}
*/
/*
protected void onPause(){
super.onPause();
mSensorManager.unregisterListener(this);
}
*/
public void onSensorChanged(SensorEvent event){
//if sensor status result is unreliable return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE){
return;
}
Sensor sensor = event.sensor;
//check sensor type
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER){
//assign directions
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
try {
//write to text file the x, y, and z values each type a sensor detects change
writeToFile(Float.toString(x), Float.toString(y), Float.toString(z));
Log.i("LIMA", "hey lily it got here!");
/*
String textFromFileString = readFromFile();
TableRow tr = new TableRow(this);
if(count%2!=0) {
tr.setBackgroundColor(Color.GRAY);
}
tr.setId(100 + count);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
//show data read from file
dataReading = new TextView(this);
dataReading.setId(200 + count);
dataReading.setText(textFromFileString);
dataReading.setPadding(2, 0, 5, 0);
dataReading.setTextColor(Color.WHITE);
tr.addView(dataReading);
//finally add data to table row
t1.addView(tr, new TableLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
count++;
Log.i("LIMA","Add row. There are now " + t1.getChildCount()+"rows");
*/
}catch (IOException e) {
e.printStackTrace();
}
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
Log.i("LIME","I pressed start!!!");
break;
case R.id.button2:
mSensorManager.unregisterListener(this);
//gps.stopUsingGPS();
Log.i("LIME","I pressed stop!!!");
}
}
/**
* writeToFile: writes data recordings of accelerometer to text file
* #param x
* #param y
* #param z
* #throws IOException
*/
void writeToFile(String x, String y, String z) throws IOException {
double latVal;
double longVal;
String s;
//get exact instance of time in which call to write is being made
Calendar c = Calendar.getInstance();
//create string to print to text using values in parameter.
GPSTracker track = new GPSTracker(this);
latVal = track.getLatitude();
Log.i("test", "this is the latitude" + latVal);
longVal = track.getLongitude();
s = "Time: " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) + ":" + c.get(Calendar.MILLISECOND) + " Coordinates: " + "x: " + x + " y: " + y + " z: " + z + " Latitude: " + latVal + " Longitude: " + longVal + "\n\r";
//s = "Time: " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) + ":" + c.get(Calendar.MILLISECOND) + " Coordinates: " + "x: " + x + " y: " + y + " z: " + z + "\n\r";
//Log.i("shucks", "it never got the gps.");
try {
//append new string to file
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND | Context.MODE_WORLD_READABLE);
//FileWriter fstream = new FileWriter(file, true);
//BufferedWriter bw = new BufferedWriter(fstream);
OutputStreamWriter bw = new OutputStreamWriter(fos);
bw.append(s);
bw.append("\n\r");
bw.close();
Log.i("LIMA","IT GOT HERE 2");
} catch(IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
/**
private String readFromFile(){
String ret = "";
try {
//open text file to read from
InputStream inputStream = openFileInput(FILENAME);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
//continue appending to stringBuilder until you've reached the end of file
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
*/
}
GPSTracker.java
package com.explorer.extractor;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class GPSTracker extends Service implements LocationListener {
// saving the context for later use
public final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 0;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 0;
// Declaring a Location Manager
public LocationManager mLocationManager;
public GPSTracker(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
/**
* Returs the Location
*
* #return Location or null if no location is found
*/
public Location getLocation() {
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
/**
* get latitude
*
* #return latitude in double
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* get longitude
*
* #return longitude in double
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
/**
* close GPS to save battery
*/
public void closeGPS() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Updating the location when location changes
*/
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}

Have you declared this permission in your manifest?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

Related

How to get GPS Distance travelled in Android with this code?

I am totally new to Android and I am stuck with a problem.
Basically what I want is when I move, my app get GPS info and display on my phone including the distance that I travelled in meter. But I don't know how to do that in Android.
This is my code.
public class MainActivity extends AppCompatActivity {
TextView tv;
TextView tv2;
ToggleButton tb;
Button currentGPS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Location location11 = null;
double Longitude1 = 0;//location11.getLongitude();
double Latitude1 = 0;//location11.getLatitude();
tv = (TextView) findViewById(R.id.textView2);
tv.setText("Ready");
tb = (ToggleButton)findViewById(R.id.toggle1);
final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
tb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(tb.isChecked()){
tv.setText("connecting..");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
100,
1,
mLocationListener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
100,
1,
mLocationListener);
}else{
tv.setText("Information not connecting");
lm.removeUpdates(mLocationListener);
}
}catch(SecurityException ex){
}
}
});
}
private final LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location1) {
Log.d("test", "onLocationChanged, location:" + location1);
double longitude = location1.getLongitude();
double latitude = location1.getLatitude();
double altitude = location1.getAltitude();
float accuracy = location1.getAccuracy();
String provider = location1.getProvider();
final double latitudeA = location1.getLatitude();
final double longitudeA = location1.getLongitude();
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latitudeA);
locationA.setLongitude(longitudeA);
Location locationB = new Location("point B");
locationB.setLatitude(latitude);
locationB.setLongitude(longitude);
distance = locationA.distanceTo(locationB);
float currentSpeed = (location1.getSpeed()*3600/1000);
String convertedSpeed = String.format("%.2f",currentSpeed);
tv.setText("Provider : " + provider + "\n\nlatitude : " + longitude + "\n\nlangitude : " + latitude
+ "\n\naltitude : " + altitude + "\n\naccuracy : " + accuracy +"/\n\nMoving distance : " + distance + "/m"
+ "\n\nCurrent speed : " + convertedSpeed + "Km/h");
}
public void onProviderDisabled(String provider) {
Log.d("test", "onProviderDisabled, provider:" + provider);
}
public void onProviderEnabled(String provider) {
Log.d("test", "onProviderEnabled, provider:" + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("test", "onStatusChanged, provider:" + provider + ", status:" + status + " ,Bundle:" + extras);
}
};
}

Run Gps as background service and Compare the received current Location Data with value in Sqlite?

I know there are many questions that have been asked regarding this and i have been going through all that from couple of days but couldn't find a reasonable answer.I am newbie to android so i have no idea how things get done.
Basically I want to know how to run GPS as a service in background like when the application is installed it starts and how to compare that data received from gps background service with data in SQLite Data Base.
you can make service like above , this service get location from GPS and network provider and insert into database in background.
package com.example.alireza.locationtracker;
import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.Hashtable;
import java.util.Map;
public class LocationTracker extends Service {
public static LocationListener gpsloclistener;
public static LocationListener netlistener;
public static LocationManager mLocationManager;
public static Location gpsLOc;
public static Location netLOc;
private static Location gpslocation;
private static Location netlocation;
public static boolean isGPSEnabled;
public static boolean isNetworkEnabled;
#Override
public void onCreate() {
super.onCreate();
gpsloclistener = new gpsloclistener();
netlistener = new netlistener();
getLocation();
// myfunc();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void getLocation() {
try
{
mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled || isNetworkEnabled)
{
if (isGPSEnabled)
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,180000,0,gpsloclistener);
}
if (isNetworkEnabled)
{
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, netlistener);//aslan bar roye network nemishe mahdodiyat gozasht
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class gpsloclistener implements LocationListener {
#Override
public void onLocationChanged(final Location location) {
if (location.getAccuracy() < 20) {
G.database.execSQL("INSERT INTO Gps_Location (Gps_lat,Gps_long,Gps_speed,Gps_time,Gps_bearing,Gps_alt,Gps_acur) VALUES ('" + location.getLatitude() + "','" + location.getLongitude() + "','" + location.getSpeed() + "','" + System.currentTimeMillis() + "','" + location.getBearing() + "','" + location.getAltitude() + "','" + location.getAccuracy() + "')");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
getLocation();
}
#Override
public void onProviderDisabled(String provider) {
}
}
private class netlistener implements LocationListener {
#Override
public void onLocationChanged(final Location location) {
G.database.execSQL("INSERT INTO Net_Location (Net_lat,Net_long,Net_speed,Net_time,Net_bearing,Net_alt,Net_acur) VALUES ('" + location.getLatitude() + "','" + location.getLongitude() + "','" + location.getSpeed() + "','" + System.currentTimeMillis() + "','" + location.getBearing() + "','" + location.getAltitude() + "','" + location.getAccuracy() + "')");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
getLocation();
}
#Override
public void onProviderDisabled(String provider) {
}
}
}
this service insert location to SQL lite database and you must start this service from somewhere like Main Activity
try{
startService(new Intent(getBaseContext(), LocationTracker.class));
}catch (Exception ex){
}
and to compare with SQL lite location, this fun calculate distance between to point
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
double v = dist * meterConversion;
return v;
}
And finally Define service to manifest
<service android:name=".LocationTracker"/>

How to switch from Gps to network provider?

Need some help. I am making an app where i get location updates from either gps or network provider. If gps is not enabled then i gave the button to enable the gps. Now what i need to do is to take updates from gps, if the gps can't get a signal then i switch over to network provider and take location updates and as soon as gps is available the switch to gps again and calculate the distance the user has travelled. I got multiple questions.
What does the getProvider and getBestProvider methods do? I think it provides the best provider that is available to the phone (correct me if i am wrong) and how can i use it to get location updates.
I need to know what providers are enabled when the user launches the app. How can i do that? I used isProviderEnabled but got confused when enabling or disabling the wifi it gives me nothing.
I tried some conditions if gps not enabled then switch to network provider but this doesn't do anything. I read many posts regarding this but couldn't figure out how to use it in my code. Any help would be greatly appreciated. Thanks. Here is my code.
public class MainActivity extends Activity {
public boolean getLocation() {
try {
isGps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
isNetwork_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!isGps_enabled && !isNetwork_enabled)
return false;
if (isGps_enabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
if (isNetwork_enabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accu = (TextView) findViewById(R.id.accu);
speed1 = (TextView)findViewById(R.id.speed);
t = (TextView)findViewById(R.id.t);
prevLatLon = (TextView) findViewById(R.id.prevLatLon);
distance = (TextView)findViewById(R.id.distance);
listView = (ListView)findViewById(R.id.listView);
listText = (TextView)findViewById(R.id.listText);
settings = (Button)findViewById(R.id.settings_button);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
List<String> providers = locationManager.getProviders(criteria, true);
for (String provider: providers){
distance.setText("Providers: " + provider);
}
provider = locationManager.getBestProvider(criteria, false);
/*isGps_enabled = locationManager.isProviderEnabled(provider);
Toast.makeText(this, isGps_enabled + "", Toast.LENGTH_SHORT).show();
isNetwork_enabled = locationManager.isProviderEnabled(provider);
Toast.makeText(this, isNetwork_enabled + "", Toast.LENGTH_SHORT).show();*/
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location loc) {
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
getLocation();
int accuracy = (int) loc.getAccuracy();
speed = (int) loc.getSpeed();
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + loc.getTime());
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(loc.getTime());
String formatted = format.format(date);
if (flag == 0) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
distanceInMeters = 0;
distanceTo = 0;
distanceBetween = 0;
timestamp = loc.getTime();
timestampmsec = 0;
hours = 0;
minutes = 0;
seconds = 0;
startTime = loc.getTime();
flag = 1;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time + "\nDistance: " + distanceInMeters + " meters"
+ "\ntimestamp: " + timestamp);
}
else {
prevLatitude = latitude;
prevLongitude = longitude;
prevSpeed = speed;
prevTime = time;
prevDistanceInMeters = distanceInMeters;
prevDistanceTo = distanceTo;
prevDistanceBetween = distanceBetween;
//prevTimestamp = timestamp;
prevTimestampmsec = timestampmsec;
prevHours = hours;
prevMinutes = minutes;
prevSeconds = seconds;
prevLatLon.setText("Previous Latitude: " + prevLatitude + "\nPrevious Longitude: " + prevLongitude +
" \nPrevious speed: " + prevSpeed + " \nTime: " + prevTime + "\nPrevious Timestamp: " + prevTimestamp);
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
timestamp = loc.getTime();
if (loc.hasSpeed()) {
Toast.makeText(MainActivity.this, "true", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "false", Toast.LENGTH_SHORT).show();
}
getDistance();
distanceTo = androidDistanceTo(prevLatitude, prevLongitude, latitude, longitude);
Location.distanceBetween(prevLatitude, prevLongitude, latitude, longitude, results);
distanceBetween = results[0];
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time + "\nDistance: " + distanceInMeters + " meters"
+ "\nTimestamp: " + timestamp);
speed = prevSpeed + speed;
distanceInMeters = prevDistanceInMeters + distanceInMeters;
distanceTo = prevDistanceTo + distanceTo;
distanceBetween = prevDistanceBetween + distanceBetween;
timestampmsec = (long) (timestamp - startTime);
seconds = TimeUnit.MILLISECONDS.toSeconds(timestampmsec);
if(seconds >= 60) {
minutes = (int) seconds / 60;
seconds = seconds % 60;
}
if(minutes >= 60){
hours = (int) minutes / 60;
minutes = minutes % 60;
}
}
distance.setText("Distance: " + distanceInMeters + " meters" + "\nDistanceTo: " + distanceTo + " meters" +
"\nDistanceBetween: " + distanceBetween + " meters" + "\nTime: " + hours + " hours " +
minutes + " minutes " + seconds + " seconds");
Toast.makeText(MainActivity.this, "Location Changed", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String arg0) {
//TODO auto generated method stub
Toast.makeText(MainActivity.this, provider + " disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
//TODO auto generated method stub
Toast.makeText(MainActivity.this, provider + " enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
//TODO auto generated method stub
}
};
}
public void getDistance(){
double dLat = Math.toRadians(latitude - prevLatitude);
double dLon = Math.toRadians(longitude - prevLongitude);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(prevLatitude))
* Math.cos(Math.toRadians(latitude)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
distanceInMeters = (6372800 * c);
}
public static double androidDistanceTo(double lat_a, double lng_a, double lat_b, double lng_b) {
Location locationA = new Location("Point A");
locationA.setLatitude(lat_a);
locationA.setLongitude(lng_a);
Location locationB = new Location("Point B");
locationB.setLatitude(lat_b);
locationB.setLongitude(lng_b);
return (locationA.distanceTo(locationB));
}
public void resetButton(View view) {
list.clear();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 30000, 0, locationListener);
}
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(locationListener);
}
getBestProvider does the following:
Returns the name of the provider that best meets the given criteria.
Only providers that are permitted to be accessed by the calling
activity will be returned. If several providers meet the criteria, the
one with the best accuracy is returned. If no provider meets the
criteria, the criteria are loosened in the following sequence: power requirement, accuracy, bearing, speed, altitude
getProvider does the following:
Returns the information associated with the location provider of the
given name, or null if no provider exists by that name.
In layman's terms you choose the provider with getProvider and the system chooses the provider with getBestProvider
You can find out what providers are enabled by looking at isProviderEnabled
Your code for starting the listeners looks fine. But you don't actually call getLocation() anywhere other than onResume() and onLocationChanged() You need to move that call out of onLocationChanged() and put it towards the end of onCreate()

Unable to unregister from sensor events in Android

According to my understanding, unregisterListener() should do the trick and I should stop getting updates from the sensors. However, this is not working. I've tried moving on to the applications menu, as well as opening another application and turning the screen off. Nothing makes the updates from the sensors stop. My code is as follows: I am trying to unregister the listeners in the onPause() and unregisterSensors() function.
public class MainActivity extends Activity implements SensorEventListener,
LocationListener {
private Location location;
private int lat, lng;
private LocationManager locationManager;
private String provider;
private SensorManager senSensorManager;
private Sensor senAccelerometer;
private Sensor senGyroscope;
private Sensor senMagneticField;
private float last_x, last_y, last_z;
private float gy_x, gy_y, gy_z;
private float mag_x, mag_y, mag_z;
private Button button;
int toggle = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("MainActivity", "In the main activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
button = (Button) findViewById(R.id.btnButton1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
toggle++;
if ((senSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null
&& (location != null)) {
if (toggle % 2 == 0) {
button.setText("Stop");
registerSensors();
}
else {
unregisterSensors();
}
}
}
});
}
public void unregisterSensors() {
Log.i("MainActivity", senSensorManager.toString());
senSensorManager.unregisterListener(this);
locationManager.removeUpdates(this);
button.setText("Start");
Log.i("MainActivity", senSensorManager.toString());
}
public void registerSensors() {
senAccelerometer = senSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senGyroscope = senSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
senMagneticField = senSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
senSensorManager.registerListener(this, senAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senMagneticField,
SensorManager.SENSOR_DELAY_NORMAL);
/* DEBUG!! */onLocationChanged(location);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
last_x = sensorEvent.values[0];
last_y = sensorEvent.values[1];
last_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = (new Date()).toString() + " x:" + last_x
+ " y:" + last_y + " z:" + last_z;
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
if (mySensor.getType() == Sensor.TYPE_GYROSCOPE) {
gy_x = sensorEvent.values[0];
gy_y = sensorEvent.values[1];
gy_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = ("Gyroscope x:" + gy_x + " y:" + gy_y + " z:" + gy_z);
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
if (mySensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mag_x = sensorEvent.values[0];
mag_y = sensorEvent.values[1];
mag_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = ("Magnetic Field x:" + mag_x + " y:" + mag_y
+ " z:" + mag_z);
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
}
protected void onPause() {
super.onPause();
senSensorManager.unregisterListener(this);
locationManager.removeUpdates(this);
}
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senMagneticField,
SensorManager.SENSOR_DELAY_NORMAL);
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
float speed = location.getSpeed();
Context context = getApplicationContext();
CharSequence text = (new Date()).toString() + " Lat:" + lat + " Long:"
+ lng + " Speed:" + speed;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It could be because the application is still running in the background, because it may not be dead yet.

GPS program works on JellyBean and KitKat but not Gingerbread

I am have written an app to find the GPS coordinates. The program works totally fine on Android 4.3 and 4.4.2 but for some reason its not working on 2.3.4 and 2.3.6. The GPS is not even turning on. Is there something additional that needs to be done to make it compatible with older APIs? I have included the following permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
This is the code :
package com.hari.gps;
import android.app.Activity;
import android.app.PendingIntent;
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.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
public static Context mContext;
public static Context getContext() {
return mContext;
}
public void setContext(Context mContext) {
MainActivity.mContext = mContext;
}
private LocationManager locationManager;
private String provider;
public static float lat, lng;
public static TextView t3, t4, t5, t6;
// SMSReceiver s;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.text1);
longitudeField = (TextView) findViewById(R.id.text2);
// 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();
// s.onReceive(getApplicationContext(), getIntent());
//
// t3.setText(s.messageReceived);
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void msg(View view) {
EditText e1 = (EditText) findViewById(R.id.edit);
String phoneno = "8056371433";
String s = e1.getText().toString();
String message, m1, m2;
t3 = (TextView) findViewById(R.id.text3);
t4 = (TextView) findViewById(R.id.text4);
t5 = (TextView) findViewById(R.id.text5);
t6 = (TextView) findViewById(R.id.text6);
m1 = String.valueOf(lat);
m2 = String.valueOf(lng);
message = m1 + " " + m2;
if (e1.getText().length() == 0)
sendSMS(phoneno, message);
else
sendSMS(s, message);
}
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(MainActivity.this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(
MainActivity.this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
boolean flag1 = true, flag2 = true;
lat = (float) (location.getLatitude());
lng = (float) (location.getLongitude());
if (lng < 0) {
lng = -lng;
flag1 = false;
}
if (lat < 0) {
lat = -lat;
flag2 = false;
}
if (flag2)
latituteField.setText("Latitude = " + lat + " N" + "\n");
else
latituteField.setText("Latitude = " + lat + " S" + "\n");
if (flag1)
longitudeField.setText("Longitude = " + lng + " E");
else
longitudeField.setText("Longitude = " + lng + " W");
// deg = Math.abs((int) lat);
// min = (int) ((lat - (float) deg) * 60.0);
// sec = (int) ((((lat - (float) deg) * 60) - min) * 60);
// if (flag2)
// latituteField.setText("Latitude = " +String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'N'+"\n");
// else
// latituteField.setText("Latitude = " +String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'S'+"\n");
// deg = Math.abs((int) lng);
// min = (int) ((lng - (float) deg) * 60.0);
// sec = (int) ((((lng - (float) deg) * 60) - min) * 60);
// if (flag1)
// longitudeField.setText("Longitude = " + String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'E');
// else
// longitudeField.setText("Longitude = " + String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'W');
}
#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();
}
}
I had to add requestlocationupdates() to make it work Strange that I was getting GPS coordinates without using the said function on Jellybean and KitKat. So the modified code is :
Criteria criteria = new Criteria();
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
//start
public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener,com.google.android.gms.maps.GoogleMap.OnMapClickListener,OnMapLongClickListener,OnMarkerClickListener,GoogleMap.OnInfoWindowClickListener {
// Update interval in milliseconds for location services
private static final long UPDATE_INTERVAL = 5000;
// Fastest update interval in milliseconds for location services
private static final long FASTEST_INTERVAL = 1000;
// Google Play diagnostics constant
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Speed threshold for orienting map in direction of motion (m/s)
private static final double SPEED_THRESH = 1;
private static final String TAG = "Mapper";
private LocationClient locationClient;
private Location currentLocation;
private double currentLat;
private double currentLon;
private GoogleMap map;
private LatLng map_center;
private int zoomOffset = 5;
private float currentZoom;
private float bearing;
private float speed;
private float acc;
private Circle localCircle;
private double lon;
private double lat;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
// Define an object that holds accuracy and frequency parameters
LocationRequest locationRequest;
// Set up shared preferences to persist data. We will use it later
// to save the current zoom level if user leaves this activity, and
// restore it when she returns.
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get a handle to the Map Fragment
// map = ((MapFragment) getFragmentManager()
// .findFragmentById(R.id.mapme_map)).getMap();
map=((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.mapme_map)).getMap();
if(map != null){
// Set the initial zoom level of the map
currentZoom = map.getMaxZoomLevel()-zoomOffset;
// Add a click listener to the map
map.setOnMapClickListener(this);
// Add a long-press listener to the map
map.setOnMapLongClickListener(this);
// Add Marker click listener to the map
map.setOnMarkerClickListener(this);
// Add marker info window click listener
map.setOnInfoWindowClickListener(this);
} else {
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
/* Create new location client. The first 'this' in args is the present
* context; the next two 'this' args indicate that this class will handle
* callbacks associated with connection and connection errors, respectively
* (see the onConnected, onDisconnected, and onConnectionError callbacks below).
* You cannot use the location client until the onConnected callback
* fires, indicating a valid connection. At that point you can access location
* services such as present position and location updates.
*/
locationClient = new LocationClient(this, this, this);
// Create the LocationRequest object
locationRequest = LocationRequest.create();
// Set request for high accuracy
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set update interval
locationRequest.setInterval(UPDATE_INTERVAL);
// Set fastest update interval that we can accept
locationRequest.setFastestInterval(FASTEST_INTERVAL);
// Get a shared preferences
prefs = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
// Get a SharedPreferences editor
prefsEditor = prefs.edit();
// Keep screen on while this map location tracking activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
// Following two methods display and handle the top bar options menu for maps
// Save the current zoom level when going into the background
#Override
protected void onPause() {
// Store the current map zoom level
if(map != null){
currentZoom = map.getCameraPosition().zoom;
prefsEditor.putFloat("KEY_ZOOM",currentZoom);
prefsEditor.commit();
}
super.onPause();
Log.i(TAG,"onPause: Zoom="+currentZoom);
}
#Override
protected void onResume() {
super.onResume();
// Restore previous zoom level (default to max zoom level if
// no prefs stored)
if (prefs.contains("KEY_ZOOM") && map != null){
currentZoom = prefs.getFloat("KEY_ZOOM", map.getMaxZoomLevel());
}
Log.i(TAG,"onResume: Zoom="+currentZoom);
// Keep screen on while this map location tracking activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
/* The following two lifecycle methods conserve resources by ensuring that
* location services are connected when the map is visible and disconnected when
* it is not.
*/
// Called by system when Activity becomes visible, so connect location client.
#Override
protected void onStart() {
super.onStart();
locationClient.connect();
}
// Called by system when Activity is no longer visible, so disconnect location
// client, which invalidates it.
#Override
protected void onStop() {
// If the client is connected, remove location updates and disconnect
if (locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
}
locationClient.disconnect();
// Turn off the screen-always-on request
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onStop();
}
}

Categories

Resources