Making the phone silent on nearing a particular location - android

I am making an android application to show the position of a user on a map, along with the users current longitude and latitude, I have also used reverse geocoding to show the address of the android device. Now I plan to add a feature that if the user is near a particular place the phone automatically switches to silent mode, for this I have made a function to check whether the phone is already silent or not. Now I want to make another one, which puts the phone in silent mode on nearing a particular location.
The method which I have made to make the phone go silent on nearing a particular location is
public void changeToSilent(Location location){
if(distanceTo(xxxx)<100)
{
if(mPhoneIsSilent==true){
}
else
{
mPhoneIsSilent = true;
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
}
Now I am calling this method in another function, which is....
public void onLocationChanged(Location location)
{
Log.d(TAG, "onLocationChanged with location " + location.toString()); Stringtext=String.format("Lat:\t%f\nLong:\t%f\nAlt:\t%f\nBearing:\t%f",location.getLatitude(),location.getLongitude(), location.getAltitude(), location.getBearing());
this.locationText.setText(text);
changeToSilent(location);
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
for (Address address : addresses) {
this.locationText.append("\n" + address.getAddressLine(0));
}
int latitude = (int)(location.getLatitude() * 1000000);
int longitude = (int)(location.getLongitude() * 1000000);
GeoPoint point = new GeoPoint(latitude,longitude);
mapController.animateTo(point);
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
Now I am calling the above function in the oncreate method. Now suppose I know the latitude and longitude of the place near which the phone should go to silent.
What I want to know is, what do I have to write in place of xxxx in the changetosilent method?

You can use the AudioManager to change the system volume levels.
here is an example:
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
//am.setStreamVolume(AudioManager.STREAM_MUSIC,6,0); //<-- use this one to set the volume
am.setRingerMode(AudioManager.RINGER_MODE_SILENT); //<-- to put on mute.
EDIT: Get a Location object and use loc.distanceBetween();

Related

LocationListener takes too long until first result

I've encountered a problem. If I turn off GPS, and then turn it on again - getLastKnownLocation() returns null.
In that case the only way to get current coordinates is the LocationListener. (Correct me if I'm wrong).
So I called the listener :
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 10, (float) 0.01, locationListener );
.....
public void onLocationChanged(final Location loc)
{
try {
addresses = geoCoder.getFromLocation( loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
{
String cityName = addresses.get(0).getLocality();
String streetName = addresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It takes about a whole minute(!) to find the location. Although once it finds it , it then updates it every second. But it still doesn't help me much.
I need to find the current coordinates as quickly as possible. How can that be done ? and why does it take the onLocationChanged is called so slowly the first time but much quicker the following times?
If the app needs more accurate and fresh location, use gps provider. Gps provider must be warmed up before getting locations. So being warmed up takes time and changes by where you are. You could use cached gps location calling getLastKnownLocation("gps") until gps hardware warmed up, and check this is too old or not.

Latitude and Longitude always getting zero (GPS and TimerTask)

Below is the code I used for getting longitude and latitude within a timertask.
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
try {
gpt = new GPSTracker(MainActivity.this);
System.out.println("Internet is present");
setContentView(R.layout.tracklayout);
TimerTask myTask = new TimerTask() {
#Override
public void run() {
try {
Log.d("flow", "" + "task()");
gpt = new GPSTracker(MainActivity.this);
lc = gpt.getLocation();
if (gpt.canGetLocation()) {
double latitude = gpt.getLatitude();
double longitude = gpt.getLongitude();
Log.d("latitude", "" + latitude);
Log.d("longitude", "" + longitude);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Reached.. ",Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
};
Timer myTimer = new Timer();
myTimer.schedule(myTask, 3000, 30000);
} catch (Exception e) {
e.printStackTrace();
}
} else {
alert.showAlertDialog(MainActivity.this,"Mobile Data is Off","Please Turn On mobile data to proceed", false);
}
}
});
Latitude and longitude are always getting zero even I manually entered co-ordinates through DDMS. There no problem with the code of GPSTracker. Outside timertask it worked fine. What is the problem with this code. Anyone please help
As you are using GPSTracker ,If GPS is not working than you can not have lat and long values for sure, you can't get an accurate location. It may take few minutes or seconds because it depends on lot of constraints like yours position inside building, weather , you device hardware quality etc as you are using sattelite to have locations, So we can say thatit depends on the device and the environment settings ( weather, Location under the sky/inside or outside building,device hardware quality etc as an example).
Why you are not using NETWORK_PROVIDER ?? if you can...
If you want to get a coarse location faster with program than you can get the location using NETWORK_PROVIDER, which isn't that accurate but can get you the location very faster.
Visit for examples
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
http://developer.android.com/guide/topics/location/strategies.html
Don't use timertask. Implement LocationListener with that activity. Write the codes in the timertask to OnLocation changed. Not needed to run in paricular time interval because we get the same data if we are in same location.

Network provider not providing location updates

This is my code to register network provider
netlocationListener = new MynetLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,interval,mttravel,
netlocationListener);
/*----------Listener class to get coordinates ------------- */
private class MynetLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(getBaseContext(), "accuracy & network provider"+loc.getAccuracy(),Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), "location changed", Toast.LENGTH_LONG).show();
CharSequence time1=android.text.format.DateFormat.format("MM-dd-yyyy hh:mm:ss", new java.util.Date());
.LENGTH_LONG).show();
String date =time1.toString();
float tsp= 0;
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = Double.toString(loc.getLongitude());
Log.v(TAG, longitude);
String latitude =Double.toString( loc.getLatitude());
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses = null;
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();
} catch (IOException e) {
e.printStackTrace();
}
String accuracy=Float.toString( loc.getAccuracy());
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName + "accuracy"
+ accuracy + "speed"+loc.getSpeed();
}
It shows true -
Toast.makeText(getBaseContext(), Boolean.toString(locationMangaer.isProviderEnabled(LocationManager.NETWORK_PROVIDER)), Toast.LENGTH_LONG).show();
If I change provider to GPS then it works perfectly but I need to get location from network provider. I checked working with internet, wifi but still no result.
Its not even entering the onlocationchanged().
For network based location, they are a lot less inaccurate than GPS, meaning you need to move the device a much larger distance to allow the signal to hook on to another network tower before
onLocationChanged() is called. Also not all network towers provide location.
I don't see where you're initializing the location manager. I'd guess you're not getting messages using network location because you're not moving enough to trigger an location change. Network position is not very accurate. I've seen network positioning be over 100ft off, and would hazard a guess that your device has a hundred foot "error radius" that you will have to move outside of to get a location update.
I've cut-n-pasted my code below, you're mileage may vary.
// see if this line gives you what you want
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// get location via network
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// get location via GPS
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

Not display location but display longitude & latitude

I am trying to display current loaction and longitude, latitude. I can easily fetch longitude & latitude but not able to display current location.
I am displaying my code below.
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
Context context;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
{
onLocationChanged(location);
//Toast.makeText(getApplicationContext(),"Hello1",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(final Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
// From here i want to get the location, as i pass current longitude &
latitude here. It passes null
in address means here it executes else instead of if.
try {
Toast.makeText(getApplicationContext(),"Hello1",Toast.LENGTH_SHORT).show();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null ) {
Address address = addresses.get(0);
// sending back first address line and locality
String result = address.getAddressLine(0) + ", " + address.getLocality();
Toast.makeText(getApplicationContext(),"result",Toast.LENGTH_SHORT).show();
}
if (addresses.size() > 0) {
String address = "";
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
Log.v("AddressTag", address);
}
else
{
Toast.makeText(getApplicationContext(),"Hello2",Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#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
}
Are you sure the Geocoder is working on your device? This is what they specify in the description of Geocoder.
The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.
This is only working on a few devices, if you really want to get the address you should use the google api. https://developers.google.com/maps/documentation/geocoding/
have you given these permissions in your manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
And is your device connected to internet?
check with Geocoder.isPresent() whether geocoder is present or not
If List is empty/null I bet that you do not have a Geocode backend service to do the actual lookups. The documentation says that "The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform."
If you want to use the Google Maps API for reverse lookup you need to include it in your project and obtain a Maps API key. "In previous versions of the SDK, the com.google.android.maps package was included in the standard Android library and system image. In the Android 1.5 SDK, that is not the case. The Android 1.5 library and system image do not include the Maps external library (com.google.android.maps). However, the Maps external library is available as part of the Google APIs add-on for the Android SDK"
Update: Since you mention that the GeoCoder.isPresent() returns true it means that a backend service exists and the problem lies elsewhere. I had a look at the Google Maps API FAQ and it mentions that lat/long to address lookups doesn't work everywhere. Have a look at this spreadsheet and set the Geocode filter to No. Is the country you're doing lookups for listed?

Android onCreate sequencing issue

I'm trying to build a string with origin and destination gps coordinates for google mapping purposes. The first thing that I need to do is to get the gps coordinates of my current location, since this is the origin point. Then, I need to concatenate these coordinates into a larger string that I use to get directions.
I have code that gets these coordinates, and also code that concatenates them into the correct string format. However, my problem is that my string building code is running first, which is leaving me with null pointer issues since the string is referencing gps coordinates that haven't processed yet.
Here it is. The gotLocation() method comes from implementing advice in this post:
Public class DirectionsActivity extends Activity {
String myLat, myLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parser parser;
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
try {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
myLat = Double.toString(lat);
myLng = Double.toString(lng);
String gps_location = myLat + " " + myLng;
Toast.makeText(getBaseContext(), "First Message", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
Toast.makeText(getBaseContext(), "Second Message", Toast.LENGTH_LONG).show();
buildString();
setContentView(R.layout.activity_directions);
}
The toast output when I run this is "Second Message" followed by "First Message". They should display in the opposite order.
Getting a location is an asynchronous operation, you don't have control on the time at which you get the answer from the system.
How would you be sure to find a satellite or cell phone mat before your toast appears ? :)

Categories

Resources