Your application wants to monitor a particular location and when
the device is near that location, you want to perform some actions. This is
very useful if you are writing an application that reminds you when you are
near to some places of interests.
One very cool feature of the LocationManager class is its ability to
monitor a specific location. This is achieved using the addProximityAlert() method.
The following code snippet shows how to monitor a particular
location so that if the user is within a five-meter radius of that location,
your application will fire a PendingIntent
object to launch the web browser:
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
public class MainActivity extends Activity {
LocationManager lm;
PendingIntent
pendingIntent;
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---use the
LocationManager class to obtain
// locations
data---
lm =
(LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void
onResume() {
super.onResume();
//---PendingIntent to launch activity if the user
// is within the
proximity of some locations---
pendingIntent =
PendingIntent.getActivity(
this, 0,
new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://www.amazon.com")),
0);
lm.addProximityAlert(37.422006, -122.084095,
5, -1, pendingIntent);
}
@Override
public void
onDestroy() {
super.onDestroy();
lm.removeProximityAlert(pendingIntent);
}
}
The addProximityAlert()
method takes five arguments: latitude, longitude, radius (in meters),
expiration (time for the proximity alert to be valid, after which it will be
deleted; -1 for no expiration), and the PendingIntent object.
Note that if the Android device’s screen goes to sleep, the
proximity is also checked once every four minutes in order to preserve the
battery life of the device. Also, your app would need the
android.permission.ACCESS_FINE_LOCATION
permission.
Come Join Our Android Courses to Learn More!
17-18 June 2013
24-25 June 2013
26 June 2013
14 June 2013
No comments:
Post a Comment