I want to know if there is any way to notify a user when he is near a particular location.
when the the user gets near the location a notification comes to his phone reminding him of his location.
I m trying following code but its not working.
public class NotifyuserActivity extends Activity {
LocationManager locMan;
double lat;
double lon;
NotificationManager notMan;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locMan=(LocationManager) getSystemService(LOCATION_SERVICE);
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,10, mylistener);
}
LocationListener mylistener= new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
CharSequence from = "AlarmManager - Time's up!";
CharSequence message = "This is your alert";
Location tasklocation=new Location(LocationManager.GPS_PROVIDER);
double dis1 = location.distanceTo(tasklocation);
tasklocation.setLatitude(22.727733);
tasklocation.setLongitude(75.886079);
if(dis1 < 200.00)
{
notMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launcher, "Click here for details", System.currentTimeMillis());
Intent notificationIntent = new Intent(NotifyuserActivity.this,NotifyuserActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifyuserActivity.this, 0, notificationIntent, 0);
n.setLatestEventInfo(NotifyuserActivity.this, from,message, pendingIntent);
notMan.notify(10001, n);
Toast.makeText(NotifyuserActivity.this,"Distance to location is: " + dis1, Toast.LENGTH_LONG).show();
}
}
};
}
here Location change code..try this.
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
System.out.println("in onlocationchanged");
String locationString=location.convert(location.getLatitude(),1);
Toast.makeText(this,"locationString=="+locationString, Toast.LENGTH_LONG).show();
double lat = location.getLatitude();
double lng = location.getLongitude();
String currentLocation = "The location is changed to Lat: " + lat + " Lng: " + lng;
Toast.makeText(this,currentLocation, Toast.LENGTH_LONG).show();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
// check in database if we have same lattitude & longitude
MySQLiteHelper m=new MySQLiteHelper(getBaseContext());
Log.d("Reading: ", "Reading all contacts..");
List<LocWiseProfileBeans> LocWiseProfile= m.getAllLocWiseProfile();
for (LocWiseProfileBeans cn : LocWiseProfile) {
String log = "Loc Name: "+cn.getLocname()+" ,Lattitude: " + cn.getLattitude()+ " ,Longitude: " + cn.getLongitude()+ " , Selected Profile :"+cn.getSelectedprofile();
// Writing Contacts to log
double distance2=00.00;
GeoPoint storedLocation=new GeoPoint(
(int) cn.getLattitude() * 1000000,(int) cn.getLongitude() * 1000000);
Location locationB = new Location("point B");
locationB.setLatitude((int) cn.getLattitude() * 1000000);
locationB.setLongitude((int) cn.getLongitude() * 1000000);
distance2=distFrom(lat,lng,cn.getLattitude(),cn.getLongitude());
if(distance2>1 )
{
Log.d("Name: ", log);
Toast.makeText(this, "Loc Name:"+log, Toast.LENGTH_SHORT).show();
Toast.makeText(this,"identical", Toast.LENGTH_LONG).show();
Toast.makeText(this,"distance2======"+distance2, Toast.LENGTH_SHORT).show();
sendnotification("Locale Notifications","You visited location " + cn.getLocname());
}
This code are use to notify the user.
protected void sendnotification (String title, String message) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = message;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = title;
CharSequence contentText = message;
Intent notificationIntent = new Intent(this, GoogleMapsActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
}
Here is function for converting longitude and latitude into miles.
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;
return dist;
}
you need to change where required as per your code....
The answer is yes.
You can register a LocationListener to LocationManager with some time or distance interval settings, then when location is changed, can compare it to what you have set to decide whether to notify the user.
GPS consumes large battery power, so you should better first use Network Location Provider, then when it's not so far to that location, start the GPS.
As the comment said, you should first move
tasklocation.setLatitude(22.727733);
tasklocation.setLongitude(75.886079);
above
double dis1 = location.distanceTo(tasklocation);
(Better, you could move these location setting out of onLocationChanged() and not hardcode Latitude/Longitude.)
This may not solve your problem ,but not doing this will NEVER make it work. So do not leave some mistake like that.
Then, I should say this code works for me (in my emulator) and I can not see other mistakes for what you give that may give you "not working".
You may check your permissions for
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Or may show the Toast result or Logcat output.
After all, more details about your "not working".
Related
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);
}
};
}
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()
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();
}
}
hi i have developed an android application for getting location and sending it to server it is working good but location update is not working it is currently running once i have to get location and send to server once in half an hour, and this process should run only for 9 hrs to 17 hrs how can i do it pls help me..!
my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
TextView tv1 = (TextView) findViewById(R.id.locationResults);
if (loc != null) {
tv1.setText("Cell ID: " + loc.getCid() + " , "
+ "Lac: " + loc.getLac() + "mcc : " + mcc
+ "mnc : " + mnc);
}
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
}
else {
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
String imei = telephonyManager.getDeviceId();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
String cdt = sdf.format(new Date());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String lat = Double.toString(latitude);
String lon = Double.toString(longitude);
String locations = Double.toString(latitude) + ","
+ Double.toString(longitude);
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
else {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
// TextView tv1 = (TextView)
// findViewById(R.id.locationResults);
if (loc != null) {
tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 10, 1,
this);
}
}
}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
// sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
+ ((lon - curStatLon) * (lon - curStatLon)));
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
You can use requestLocationUpdates of LocationManager Class
requestLocationUpdates (long minTime, float minDistance, Criteria
criteria, PendingIntent intent)
So, the first param you can specify as 30 mins according to your requirement.
To keep track of hours elapsed, you can have something like :
var1 = System.CurrentTimeMillis(); //Get time when service started
In onLocationChanged()
var2 = System.CurrentTimeMillis();
Now calculate var2-var1 to get elapsed time. if >17 hrs, removeUpdates from locationManager
I have a similar project going on, I am using a Service for this, fired by an AlarmManager.
Check here for more info.
The approach provided by Schaemelhout and the approach taken by library referred to in the comments is the only workable solution I have found.
Using an AlarmManager to wake your service guarantees the service is periodically invoked/restarted. This serves to counteract any power saving actions that the OS/phone might hit your service with in the mean time.
Registering a location listener from your alarm BroadcastReceiver wakes up the GPS (the GPS would not normally be running if the phone is asleep). In your alarm BroadcastReceiver you will need to take and hold a WakeLock and stay awake until results are passed back to the listener.
The down side to this approach is that it takes a while for a location to be available and the accuracy may be bad. Your service might have to wait a while until acceptable accuracy is achieved (the Location accuracy value can be wrong, so it might be be best to wait for a few samples). The whole approach will need to be tuned to your required update frequency and accuracy requirements. If you need very frequent and accurate updates I suspect holding a wake-lock and keeping the GPS alive might be the only way to go.
I also tried using the lm.requestLocationUpdates() using a PendingIntent. This did faithfully wake up my service and pass it an Intent, but if the GPS was sleeping prior to the wake up the Intent lacked a location.
I am just testing out the onLocationChanged method in Android , I have implemented a way that when I click a button the app returns a String with the new lat and lng values. But now I am trying to show the results automatically every time the location changes. This is what I have so far to do so:
location manager
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int minTime = 30000;
LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
MyLocationListener myLocListener = new MyLocationListener();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, minTime, 1, myLocListener );
onlocationchanged
public void onLocationChanged(Location loc) {
if(loc != null){
lat1 = loc.getLatitude();
lng1 = loc.getLongitude();
currentlocation = "Location changed to lat: " + lat + "" + "lng: " + lng1 ;
Context context = getApplicationContext();
CharSequence text = currentlocation;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I have set the requestlocationupdates method to request and update every 60000 millseconds
My problem is that the application never toasts the lat and lng values when the location changes. I have tested the app with the emulator and tried telneting the lat and lng values. And I have also drove around in my car to see if the values change.
Try:
currentlocation = "Location changed to lat: " + String.valueOf(lat1) + "" + "lng: " + String.valueOf(lng1) ;
and for test you can just use:
requestLocationUpdates(LocationManager.GPS_PROVIDER...