I am trying to write a simple app that takes the users current location and notifies them when they come near this location later. In my code I have it set up so that when the app starts it starts requesting location updates. Then when the button is pressed it takes the last known location and creates a proximity alert around that. my problem however is that when i press the button on both the emulator and the real phone it quickly crashes and i cant seem to find a reason why. is there an infinite loop i am some how missing? if there is a way to see the error messages from my phone that would also be very helpful.
Here is my code:
MainActivity.java
package com.YdidApplications.shotgun;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener
{
private ImageButton flagButton;
LocationManager lm;
double lat=0,long1=0; //Defining Latitude & Longitude
float radius=5; //Defining Radius
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER,
10000, //Update every 10 sec
10, (LocationListener) this);
flagButton = (ImageButton) findViewById(R.id.FLAG);
onFlagPress();
}
public void onFlagPress()
{
flagButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
location();
}
});
}
public void location()
{
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
lm.getLastKnownLocation(LOCATION_SERVICE);
Intent i= new Intent("com.adnan.proximityalert"); //Custom Action
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
lm.addProximityAlert(lat, long1, radius, -1, pi);
}
#Override
public void onLocationChanged(Location location) {
lat= location.getLatitude();
long1 = location.getLongitude();
Toast.makeText(null, lat+", "+long1, 0);
}
#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
}
}
ProximityReciever.java
package ProximityReciever;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.widget.Toast;
/*This is the Reciever for the Brodcast sent, here our app will be notified if the User is
* in the region specified by our proximity alert.You will have to register the reciever
* with the same Intent you broadcasted in the previous Java file
*
* #Author: Adnan A M
*/
public class ProximityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
// The reciever gets the Context & the Intent that fired the broadcast as arg0 & agr1
String k=LocationManager.KEY_PROXIMITY_ENTERING;
// Key for determining whether user is leaving or entering
boolean state=arg1.getBooleanExtra(k, false);
//Gives whether the user is entering or leaving in boolean form
if(state){
// Call the Notification Service or anything else that you would like to do here
Toast.makeText(arg0, "Welcome to my Area", 600).show();
}else{
//Other custom Notification
Toast.makeText(arg0, "Thank you for visiting my Area,come back again !!", 600).show();
}
}
}
Any advise would be greatly appreciated.
Thanks,
Logan
Related
First of all this is not a duplicate of any other question on the site. I've seen location updates using Service and Google API both.
Here is the link which uses the service to get location updates
This is the link which uses Google API for the same. This works perfectly.
I've tried both, but in case of service, it is not working. But the 1st link's code is working perfectly fine, and gives location updates correctly. But I think It can't get update when the app is in background.
I want that code inside a service, which can continuously get location updates even my app is in background.
But can't figure out how to merge this two codes. If you are asking what I've tried? Than I've just copy the common methods in the service class. But it gives me too many errors :(
If there are alternative available for this please suggest me. I'm new to android.
Thanks in advance!
Try:
Service.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"GoogleApiClient connection has been suspend",Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"GoogleApiClient connection has failed",Toast.LENGTH_LONG).show();
}
and MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,GPSService.class);
startService(i);
}
I'm working on an Android Project where i'm using AddProximityAlert method, as you already know this method let you set a proximity alert for the location given by the position (latitude, longitude) and the given radius, and notify you if you are so close to it.
so i was working on that for three days ago and i was getting the same probleme again and again..
in bref: this is my simple code.
#MainActivity.java
package com.example.proximityalert;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener {
LocationManager lm;
//Defining Latitude & Longitude
double lat=37.422006 ,long1=-122.084095;
//Defining Radius
float radius=1000;
//Intent Action
String ACTION_FILTER = "com.example.proximityalert";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//i'm registering my Receiver First
registerReceiver(new ProximityReciever(), new IntentFilter(ACTION_FILTER));
//i'm calling ther service Location Manager
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
//for debugging...
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
//Setting up My Broadcast Intent
Intent i= new Intent(ACTION_FILTER);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
//setting up proximituMethod
lm.addProximityAlert(lat, long1, radius, -1, pi);
}
#Override
//just For debugging to See the distance between my actual position and the aproximit point
public void onLocationChanged(Location newLocation) {
Location old = new Location("OLD");
old.setLatitude(lat);
old.setLongitude(long1);
double distance = newLocation.distanceTo(old);
Log.i("MyTag", "Distance: " + distance);
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
#ProximityReceiver.java
package com.example.proximityalert;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import android.widget.Toast;
public class ProximityReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Key for determining whether user is leaving or entering
String key = LocationManager.KEY_PROXIMITY_ENTERING;
//Gives whether the user is entering or leaving in boolean form
boolean state = intent.getBooleanExtra(key, false);
if(state){
// Call the Notification Service or anything else that you would like to do here
Log.i("MyTag", "Welcome to my Area");
Toast.makeText(context, "Welcome to my Area", Toast.LENGTH_SHORT).show();
}else{
//Other custom Notification
Log.i("MyTag", "Thank you for visiting my Area,come back again !!");
Toast.makeText(context, "Thank you for visiting my Area,come back again !!", Toast.LENGTH_SHORT).show();
}
}
}
*#the probleme is when i run the program , the BroadcastReceiver(ProximityReciever) never never called by the system even if i'm veryyy close to the proximit point, and even if the debugger shows me that distance between the two locations is < 1000m :/
I just figured out somthing about this topic and why the addProximityAlert sames to be not working, I'm sharing this with you because I noticed that some people asked the same question before and they don't get any answer!
The answer was just in front of me but i didn't pay attention to it, so when i was reading the Android officiel documentation (here) i saw this sentence "Due to the approximate nature of position estimation, if the device passes through the given area briefly, it is possible that no Intent will be fired"
what is that mean? it means when you are testing your app on the AVD and u send a gps coordinates(latitude, longitude) from the DDMS to AVD its really hard to
simulate the real aspect of a gps, (because in the first place u pick some point to be your proximPoint and just after that you choose anthor point very far from the proximPoint to see if its work) and thats not what it's happing with a real device.
so the solution is to test your app on a real device or with the DDMS try to change the coordiantes very slowly until you are in the zone wanted.
I'm very new to android. I want to create an application that turns off all sounds at the selected time. I created a service with some code and in Eclipse there's no errors, but when I press the button nothing happens. I can see in Application Manager that my program and the service SilentHours are running. Here's my code:
MainActivity.java
package com.example.silencecontrol;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_NAME = "sending silentHour value to service SilenceHours";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setSilenceHours(View view) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
TextView textView1 = (TextView)findViewById(R.id.textView1);
if(editText1.length() > 0) {
Intent intent = new Intent(this, SilentHours.class);
String editText1String = editText1.getText().toString();
int silentHour = Integer.parseInt(editText1String);
intent.putExtra(EXTRA_NAME, silentHour);
this.startService(intent);
} else {
textView1.setText("Please enter the silence hour. ");
}
}
}
SilentHours.java
package com.example.silencecontrol;
import java.util.Calendar;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
public class SilentHours extends Service {
public SilentHours() {
}
protected void onHandleIntent(Intent intent) {
int silentHour = Integer.parseInt(intent.getStringExtra(MainActivity.EXTRA_NAME));
Calendar calendar = Calendar.getInstance();
int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
if(currentTime >= silentHour) {
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
And by the way I can't #Override the onHandleIntent method. If I put the #Override annotation I get error:
The method onHandleIntent(Intent) of type SilentHours must override or implement a supertype method.
Is that annotation necessary?
The method you are looking for is named onStartCommand, not onHandleIntent.
And no, it's not necessary to add this annotation to an overriden method, it's just a very good practice as you can get sure that you respected the signature of the super class.
Let you IDE help you when you code. Simply type "on" then ask for completion to see which method you can override.
I am trying to build an android application that silences a call when a person waves his/her hand over the phone as it starts ringing/vibrating using the Proximity sensor.
I am new to android development.
I have tried to make the application check if the phone is in State-Rining. If it is, then the app checks if the value of the proximity sensor ==0 (near value). If the value for proximity sensor is 0, it implies that the sensor was cover during the ringing ad hence it should mute the call.
But it is still in ringing state.
I think the problem is that the ServiceReceiver only checks for the value of the proximity sensor just as the phone starts to ring. If the sensor value is not zero at that instant, the phone doesn't get silenced.
So how can I make it check for a change in value of proximity sensor throughout the ringing or incoming call such that as soon as the sensor value turns to zero, call is silenced
The first class "mainactivity" contains the code for proximity sensor.
package example.ringcheck;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
static TextView proxText;
SensorManager sm;
Sensor proxSensor;
static float proxValue = 8;
// static boolean muteCall = false;
private AudioManager amanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText = (TextView) findViewById(R.id.ProximityTextView);
sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
proxText.setText(String.valueOf(event.values[0]));
proxValue = event.values[0];
Log.d("SENSOR VALUE", "********" + proxValue + "*******");
}
}
The second class "ServiceReceiver" contains the code for proximity sensor.
package example.ringcheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.telephony.TelephonyManager
import android.util.Log;
public class ServiceReceiver extends BroadcastReceiver {
private AudioManager amanager;
// static boolean isRinging = false;
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
// isRinging = true;
if (MainActivity.proxValue == 0) {
amanager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
amanager.setRingerMode(0x00000000);
// isRinging = false;
}
Log.d("MPR", "Its Ringing");
}
}
}
Thanks in advance :-)
Instead of
amanager.setRingerMode(0x00000000);
Try
amanager.setStreamMute(AudioManager.STREAM_RING, true);
I have a little problem... I have made an Android application which extends the webview. The webview Html page with a map on like this: Map example, it was also here I got my inspiration. My onCreate method looks like this:
super.onCreate(savedInstanceState);
//Removes the title bar in the application
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Creation of the Webview found in the XML Layout file
browserView = (WebView)findViewById(R.id.webkit);
//Removes both vertical and horizontal scroll bars
browserView.setVerticalScrollBarEnabled(false);
browserView.setHorizontalScrollBarEnabled(false);
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Enable Javascripts
url = "http://www.my-homepage.dk/map_example.html";
browserView.getSettings().setJavaScriptEnabled(true);
//The website which is wrapped to the webview
browserView.loadUrl(url);
So when My application gets a GPS location, it invokes this method:
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
StringBuilder buf=new StringBuilder(url);
buf.append("?");
buf.append("lon=");
buf.append(String.valueOf(location.getLongitude()));
buf.append("&");
buf.append("lat=");
buf.append(String.valueOf(location.getLatitude()));
browserView.loadUrl(buf.toString());
}
So it basically just loads another URL.... But, my problem is, 1. it keeps the orignal website "map image", i imagined it would "unload" the page, and 2. When the second url is loaded, it takes quite a long time before it is finished, and when i am testing on my HTC Desire, it sometimes doesnt show the second loaded page (the map with location) before it turns the screen off and lock, or if i go out and in the application, that sometimes helps too...
Hope you can help :)
A suggestion - in onLocationChanged, make locationFound(); the first statement instead of the last.
It would be good to stop the listener immediately, as the loadUrl statement could take some time to complete, while the provider could be sending more updates.
Here is the solution... The GPS listener apparently broadcast more than once ;) so, when the GPS finds a location it loads the url and then stops broadcasting.
So the problem before was, that it sent loads of URL's to the html page, and therefore never just loaded 1 single url. And i just simplified the onLocationChanged a bit.
public void locationFound(){
myLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
String lon = "lon="+String.valueOf(location.getLongitude());
String lat = "lat="+String.valueOf(location.getLatitude());
browserView.loadUrl(url+"?"+lon+"&"+lat);
locationFound();
}
Here is the SourceCode for the application:
package com.webview;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewTest extends Activity implements LocationListener{
private WebView browserView;
private static String PROVIDER="gps";
private LocationManager myLocationManager=null;
private String url;
private boolean LocFound = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Removes the title bar in the application
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Creation of the Webview found in the XML Layout file
browserView = (WebView)findViewById(R.id.webkit);
//Removes both vertical and horizontal scroll bars
browserView.setVerticalScrollBarEnabled(false);
browserView.setHorizontalScrollBarEnabled(false);
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Enable Javascripts
url = "http://www.test.dk/test.html";
browserView.getSettings().setJavaScriptEnabled(true);
//The website which is wrapped to the webview
browserView.loadUrl(url);
}
#Override
public void onResume() {
super.onResume();
myLocationManager.requestLocationUpdates(PROVIDER, 0,
0,
this);
}
#Override
public void onPause() {
super.onPause();
myLocationManager.removeUpdates(this);
}
public void locationFound(){
myLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
String lon = "lon="+String.valueOf(location.getLongitude());
String lat = "lat="+String.valueOf(location.getLatitude());
browserView.loadUrl(url+"?"+lon+"&"+lat);
locationFound();
}
#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
}
}