i am developing an gps program in that i am getting gps values for every 5 minutes,
and it is working great, but i have to store the values which i get. it has been refreshed for every 5 minutes and i have only one text view so that it deletes the old values when the new one is refreshed.
this is my code.
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);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); 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");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#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 location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// 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;
}
Thank you.
You can store your Textview's value into a file for persistance storage. Study my answer properly, I am adding a file store method in your existing code,
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);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); 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");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// 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;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File("sdcard/gpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to write following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well you have plenty of persistence options, but in this case the best is using SharedPreferences
No one can say for sure without knowing exactly what you need to do with the saved data. ArrayList is a good option if you need to store it temporarily. You can create a new ArrayList then put the value in there at the same time that you use it in setText(). If you want something permanent then you will probably want to store it in a DB or a file. Check out Storage Options
Also, in this case, a good idea may be to store it in an ArrayList temporarily then use that list to transfer them to a file or DB for permanent storage if that's what you want
Another way to store it temporarily, and possibly save somewhere later would be a HashMap. Maybe something in the form of HashMap<String, HashMap<String, String>>. Since we don't know your exact intentions with the data, examples could be endless but maybe this will give you a good starting point so you can decide what will work best for you then you can find many examples all over SO and the Google for your choice
Related
I am getting locations from network only not gps.i need gps locations not network provider..but as i see in my logfile..i am only getting network location which are not accurate.so i need to have gps locations..please help me out where i am doing wrong.thanks in advance..
if(isNetworkEnabled)
{
try
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
ll = new LocationListener() {
public void onLocationChanged(Location loc)
{
try {
location = loc;
latitude = location.getLatitude();
longitude = location.getLongitude();
logFile log=new logFile();
dt = location.getTime();
log.createFile("Location Changed NETWORK:"+latitude+""+longitude+"time:"+dt);
setdateAndtime(dt);
} catch (Exception e) {
String errMsg= e.getClass().getName() + " " + e.getMessage();
logFile log=new logFile();
log.createFile("Error in GPS TRACKER When Location Changed"+errMsg+"\n");
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
dt = location.getTime();
setdateAndtime(dt);
logFile log=new logFile();
log.createFile("Location From NETWORK:" + latitude + " " + longitude +
"time:" + dt + ":" + location.getProvider() + location);
}
}
catch(Exception e)
{
System.out.println(e+"Error MSg");
}
}
if(isGPSEnabled)
{
try
{
if (location != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0,
ll = new LocationListener() {
public void onLocationChanged(Location loc)
{
try {
location = loc;
latitude = location.getLatitude();
longitude = location.getLongitude();
logFile log=new logFile();
dt = location.getTime();
log.createFile("Location Changed GPS:"+latitude+""+longitude+"time:"+dt);
setdateAndtime(dt);
} catch (Exception e) {
String errMsg= e.getClass().getName() + " " + e.getMessage();
logFile log=new logFile();
log.createFile("Error in GPS TRACKER When Location Changed"+errMsg+"\n");
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
dt = location.getTime();
setdateAndtime(dt);
logFile log=new logFile();
log.createFile("Location From GPS:" + latitude + " " + longitude +
"time:" + dt + ":" + location.getProvider() + location);
}
Change order and conditions.
Your code is..
if (enable_network)
{
// get location from network provider
}
if (enable_gps)
{
// get location from gps provider
}
Your code always receive location from network provider(if it was on).
So, you should check gps provider condition first and check network provider next.
Change code like this
if (enable_gps)
{
// get location from gps provider
}
else (enable_network)
{
// get location from network provider
}
else
{
// can not receive location data
}
I things your testing your application in the Indoor,As the GPS does not work in indoor and that why it is working with your network...try to check the application by moving outside...
Avinash I believe you are from India. Why is that important? because in India even on outside I was not able to get the location from GPS via LocationManager I have ran so many tests on GPS from LocationManager. It seems to return location very rarely from GPS provider.
Solution
Use LocationClient (Google Play services) to retrieve the current location. Google play services are very accurate and retrieves location from Network, GPS and Wifi, If available.
And there are more chances that you can Location. Follow this guide
I want to achieve something which I though was simple enough, but now I end up being a little confused.
I want to get the coordinates of the user in this way
Is there a GPS provider?
If yes, get the coordinates from gps
Else if there is a network provider get them from there
I used both locationManager and onLocationChange(), and the new API with locationClient but I can't get the coordinates from my device's GPS, only from network.
This is the one with the locationManager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use default
Criteria criteria = new Criteria();
String 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.");
// new AlertDialog.Builder(v.getContext()).setMessage("Provider " + provider + " has been selected.").show();
onLocationChanged(location);
System.out.println(location.getLatitude());
Intent intent = new Intent(getApplicationContext(),DriveMeActivity.class);
intent.putExtra("monument", monument);
intent.putExtra("latitude", location.getLatitude());
intent.putExtra("longitude",location.getLongitude());
startActivity(intent);
} else {
new AlertDialog.Builder(con).setMessage("Location not available").show();
System.out.println("Location not available");
System.out.println("Location not available");
}
and this is the one with locationClient
GooglePlayServicesUtil.isGooglePlayServicesAvailable(v.getContext())
if(mLocationClient.getLastLocation()!=null)
Toast.makeText(getApplicationContext(),
mLocationClient.getLastLocation().getLongitude()+ "|" +
mLocationClient.getLastLocation().getLatitude() ,
Toast.LENGTH_SHORT).show();
here's the complete code to find the best available provider whether gps or network and show settings menu to enable the location services.
public class DSLVFragmentClicks extends Activity implements LocationListener {
private final int BESTAVAILABLEPROVIDERCODE = 1;
private final int BESTPROVIDERCODE = 2;
LocationManager locationManager;
String bestProvider;
String bestAvailableProvider;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BESTPROVIDERCODE) {
if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestProvider);
}
} else {
if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestAvailableProvider);
}
}
}
public void getLocation(String usedLocationService) {
Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
long updateTime = 0;
float updateDistance = 0;
// finding the current location
locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);
}
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.main);
// set a Criteria specifying things you want from a particular Location Service
Criteria criteria = new Criteria();
criteria.setSpeedRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
criteria.setAltitudeRequired(false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// finding best provider without fulfilling the criteria
bestProvider = locationManager.getBestProvider(criteria, false);
// finding best provider which fulfills the criteria
bestAvailableProvider = locationManager.getBestProvider(criteria, true);
String toastMessage = null;
if (bestProvider == null) {
toastMessage = "NO best Provider Found";
} else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
// show settings menu to start gps or network location service
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
} else {
getLocation(bestAvailableProvider);
}
toastMessage = bestAvailableProvider + " used for getting your current location";
} else {
boolean enabled = locationManager.isProviderEnabled(bestProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTPROVIDERCODE);
} else {
getLocation(bestProvider);
}
toastMessage = bestProvider + " is used to get your current location";
}
Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
// getting the street address from longitute and latitude
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
String addressString = "not found !!";
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder stringBuilder = new StringBuilder();
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
addressString = stringBuilder.toString();
locationManager.removeUpdates(this);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderEnabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderDisabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
I have already explained a lot in comments but if you still don't understand something then feel free to ask.
I hope you are trying it on a device and you have tried it out in open. In most cases You won't get gps coordinates until you step out.
Most probably you don't have the location fix and GPS locationProvider takes time to get the location fix in compare to network location provider.
What can you do is that you can use the last known location fix.
String locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.NETWORK_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
But the further problem is that you might have the old location fix and network provider can provide you better location.
Android has really good documentation on this and sample code to find the best known location.
http://developer.android.com/guide/topics/location/strategies.html
In my app I have a list of round 9 places with the associative lat long positions, and the end goal is to notify the user if they are within about half a mile of any of the locations.
What would be the best way to do this? This is what I have so far.
distanceFromListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
List<JSONObject> centres = sortVenuesByNearest(location);
Log.d("FUApp", "distanceFromListener setting location");
haveLocation = true;
theLocation = location;
float accuracy = location.getAccuracy();
for (JSONObject centre : centres) {
try {
Double distance = Double.valueOf(centre.getString("distanceTo"));
String name = centre.getString("name");
Integer venueID = Integer.valueOf(centre.getString("id"));
if (distance < 804.672) {
Bundle mBundle = new Bundle();
Double miles = (distance * 0.00062137);
DecimalFormat df = new DecimalFormat("#.##");
String miles2 = df.format(miles);
mBundle.putString(ExtraKeyCentreName, name);
mBundle.putString(ExtraKeyCentreDist, miles2 + " miles away");
mBundle.putString(ExtraKeyCentreJSON, centre.toString());
mBundle.putString(ExtraKeyCentrePostcode, "none");
sendNotification(ActivityCentrePage.class, "Visit " + name, "You're half a mile from " + name + ". Why not come for a visit?", R.drawable.ic_launcher, venueID, mBundle);
} else {
cancelNotification(venueID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
Boolean notify_if_close = sp.getBoolean(SettingsNotifyIfClose, true);
if (notify_if_close) {
locationService.requestLocationUpdates(LocationManager.GPS_PROVIDER, 50, 100, distanceFromListener);
}
That works, but if the user cancels a notification saying there close, when the location is next updated it will pop up again, which will get annoying. Would a suitable alternative be put a big minTime, say half an hour on the requestLocationUpdates?
What would be the best way to do this?
Use geofences with the LocationClient from the Play Services SDK, or try proximity alerts with LocationManager.
Use a service for tracking coordinates...
try this link, it may help u..
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
Hi can any body show me how to run this code in service without activity, i have done this code in an activity but i dont want it to be an application i need it to be in a service only just to display it on service thank you i have tried but my activity displaying for once in 30 mins.
this is my code:
public class gps extends Activity implements LocationListener {
LocationManager manager;
String closestStation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
cur_cal.add(Calendar.MINUTE, 15);
Log.d("Testing", "Calender Set time:" + cur_cal.getTime());
Intent intent = new Intent(gps.this, gps_back_process.class);
PendingIntent pintent = PendingIntent.getService(gps.this, 0,
intent, 0);
AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP,
cur_cal.getTimeInMillis(), 1000 * 60 * 15, pintent);
alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(),
pintent);
Log.d("Testing", "alarm manager set");
Toast.makeText(this, "gps_back_process.onCreate()",
Toast.LENGTH_LONG).show();
}
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);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); 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");
} else
{
tv.setText("Last known location not found. Waiting for updated location...");
}
manager.requestLocationUpdates(providerName, 1000*60*30 , 1 , this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( 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) {}
// 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;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File(Environment.getExternalStorageDirectory() + "/GpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm, dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
// text+=","+currentDateandTime;
buf.append(text + "," + currentDateandTime);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.extends service class instead of Activity class and
2. put your code into oncreate()
3.add your service into manefest.
4.call service from activity once like
Intent service = new Intent(context, localService.class);
context.startService(service);
follow this tutorial.
I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value. Below is my code
public void getValue() {
LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS IS "+gpsEnabled);
if (!gpsEnabled) {
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"));
sendBroadcast(poke);
}
}
SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
try {
getBatteryLevel();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocation = location;
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
address = getAddress();
alt = location.getAltitude();
if (meterFootFlag) {
diameter = location.getAccuracy();
} else
diameter = location.getAccuracy() / 3.28084;
} else {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
} catch (Exception e) {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
Also I have added permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
but I am getting a null value for the location.
Any ideas on how I can get the location?
Your code is correct just wait until GPs get altitude from a satellite it may take mroe than 1 minute.
try:
public Location showLocation(){
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Class model, save latitude and longitude
NavegadorCoordenadas locate = new NavegadorCoordenadas();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, false);
Location loc = getLastKnownLocation(lm);
locate.setLatitude(loc.getLatitude());
locate.setLongitude(loc.getLongitude());
return loc;
}
private Location getLastKnownLocation(LocationManager location) {
List<String> providers = location.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = location.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Make sure that you are checking on DEVICE only.. In Emulator it will give Null Values for GPS as it is running in the system so it doesnot have permission for GPS
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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"));
sendBroadcast(poke);
}
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
locationListener);
Now make MyLocationListener class in same activity.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
System.out.println("MESSAGE:"+cityName);
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude+"\t city name:"+cityName;
Log.v("OUTPUT, s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Run your application in Actual device.
you can figure out that automatic start GPS and see console logcat.
Make sure to open Permissions through the
Settings--> Applications-->YourApp-->permissions
And another reason could be delay, it takes time to connect to network, somethimes more than a minute