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.
Related
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();
}
}
I have developed an application get location but i need to save it to server using aspx webpage.
I have created tables on the webpage and i need to save these lat,long to the webpagepage using the unique id as imei?
I have created a table with imei, latlong, datetime
aspx name /http://Log.aspx/
can anybody help me please I have searched many but I couldn't understand.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
// initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// check if GPS is enabled
// else switch on gps
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
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);
}
}
else {
// get a location provider from location manager
// empty criteria searches through all providers and returns the
// best one
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");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("disabled", false);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
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);
}
}
else {
// get cell id
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);
// to write it to file
appendData("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 15, 0,
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");
// to write the file..
appendData(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}
I wrote a WS few months back like this:
<%# WebService Language="VBScript" Class="DataIns" %>
Imports System
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Globalization
<WebService(Namespace:="http://www.mysite.org/webservices/")> Public Class DataIns :Inherits WebService
<WebMethod()> Public Function devIns (ByVal dm As String) As String
Dim strArr() As String
Dim rtnVal As String
strArr = dm.split("^")
Dim connection As SqlConnection
Dim connection1 As SqlConnection
Dim connection2 As SqlConnection
Dim cmd As SqlCommand
Dim connectionString As String
connectionString = ConfigurationManager.ConnectionStrings("sqlsds").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmdtrans As SqlCommand
Dim cmdCheck As SqlCommand
Dim result as String
Dim sqltrans as String
Dim notes as String
Dim notes1 As String
sqltrans= "select dbo.fnCheckBlackList(#p_imei)"
cmdtrans=new sqlcommand(sqltrans,connection)
cmdtrans.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection.Open()
notes=cmdtrans.ExecuteScalar()
Catch ex As Exception
notes = ex.Message
Finally
connection.Close()
End Try
notes = If(IsDBNull(notes),"","")
if notes.Trim().Equals("TIMEUP") then
Context.Response.Output.Write("Save Completed Wipeout")
Context.Response.End()
return string.Empty
else
connection1 = New SqlConnection(connectionString)
result = "select dbo.fnCheckImeiDateWise(#p_imei)"
cmdCheck=new sqlcommand(result,connection1)
cmdCheck.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection1.Open()
notes1=cmdCheck.ExecuteScalar()
Catch ex As Exception
notes1 = ex.Message
Finally
connection1.close()
End Try
if notes1.Trim().Equals("FINE") then
connection2 = New SqlConnection(connectionString)
cmd = New SqlCommand("dbo.spInsertDeviceData", connection2)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#p_imei", strArr(0))
cmd.Parameters.AddWithValue("#p_location", strArr(1))
cmd.Parameters.AddWithValue("#p_aic", Integer.Parse(strArr(2)))
cmd.Parameters.AddWithValue("#p_adc", Integer.Parse(strArr(3)))
cmd.Parameters.AddWithValue("#p_ail", strArr(4))
cmd.Parameters.AddWithValue("#p_adl", strArr(5))
cmd.Parameters.AddWithValue("#p_tsss", Double.Parse(strArr(6)))
cmd.Parameters.AddWithValue("#p_ts", Double.Parse(strArr(7)))
cmd.Parameters.AddWithValue("#p_tsgp", Double.Parse(strArr(8)))
cmd.Parameters.AddWithValue("#p_tvpc", Double.Parse(strArr(9)))
Try
connection2.Open()
rtnVal = cmd.ExecuteNonQuery()
Catch ex As Exception
rtnVal = ex.Message
Finally
connection2.Close()
End Try
'Context.Response.Output.Write(rtnVal)
Dim parameterString As String
Dim dow2 As String
parameterString = ConfigurationManager.AppSettings("FREQUENCY")
parameterString = parameterString + "|"
parameterString = parameterString + getNewTime(ConfigurationManager.AppSettings("UPDATEAT1"))
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFWEEK1")
dow2 = ConfigurationManager.AppSettings("DAYOFWEEK2")
if String.IsNullOrEmpty(dow2) then
else
parameterString = parameterString +"*"
parameterString = parameterString + dow2
end if
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFMONTH")
Context.Response.Output.Write("Save Completed" + "|"+ parameterString)
Context.Response.End()
return string.Empty
else
Context.Response.Output.Write("ERROR")
Context.Response.End()
return string.Empty
End If
End If
end function
end class
and this was called like
http://www.mysite.org/DataIns.asmx/dIns?dm=<data-separated=by-^>
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...
I used this tutorial to write my app. I use the DDMS Location Manager to change my location virtually.
Unfortunally I always get a location of 0.0 for long and lat. Even if I switch them later in the prog with locationchanged-method I get 0.0.
Code is this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---use the LocationManager class to obtain GPS locations---
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastLoc = lm.getLastKnownLocation("gps");
curLocation = "Standort: \nLatitude: " + lastLoc.getLatitude() + "\nLongitude: " + lastLoc.getLongitude();
upperText = (TextView) findViewById(R.id.TextView01);
upperText.setText(curLocation);
}
and
#Override
public void onLocationChanged(Location loc)
{
if (loc != null) {
Toast.makeText(getBaseContext(),
"Location changed : Lat: " + loc.getLatitude() +
" Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}
if (loc != null)
{
upperText.setText(curLocation + "\n\nStandort: \nLatitude: " + loc.getLatitude()
+ "\nLongitude: " + loc.getLongitude());
}
}
Something's missing, but I don't know what... :/
I'd be really pleased if anyone could help =)!
go to maps default application and allow user to allow latitude and longitude option .In our application when the GPS signal blinks and when it stops we will get the latitude and longitude.It worked for me