My app uses geofences to notify the user when the enter a location, a notification gets displayed when the user enters the location.
what im trying to to is get the triggering geofences convert them to a string, then send them to another activity so that they can be displayed in a list view.
Ive watched tutorials online on how to makes list views and how to send data using intents but what im trying to do just doesn't seem to work.
EDIT
I'm starting the list view PageActivity using a intent with startActivity from another class the MainActivity.
Goals
If the user clicks on the notification from anywhere especially from outside the application it will open the app with the list view being filled with the geofence details. If the user opens the app just opens the app the from the launcher, then the same to happen. The list to be filled with any geofences that were triggered.
GeofenceTransitionsIntentService Class:
public class GeofenceTransitionsIntentService extends IntentService {
protected static final String TAG = "GeofenceTransitionsIS";
/**
* This constructor is required, and calls the super IntentService(String)
* constructor with the name for a worker thread.
*/
public GeofenceTransitionsIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
}
#Override
public void onCreate() {
super.onCreate();
}
/**
* Handles incoming intents.
* #param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
#Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()){
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the Transistion Type
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transisition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transistion details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
headsUpSmsNotifaction(geofenceTransitionDetails);
Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else{
// Log the error
Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
}
}
/**
* Gets transition details and returns them as a formatted string.
*
* #param context The app context.
* #param geofenceTransition The ID of the geofence transition.
* #param triggeringGeofences The geofence(s) triggered.
* #return The transition details formatted as String.
*/
private String getGeofenceTransitionDetails(Context context, int geofenceTransition, List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList triggeringGeofencesIdsList = new ArrayList();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
private void headsUpSmsNotifaction(String notificationDetails){
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(this, sendSmsReceiver.class);
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(this,44,notificationIntent,0);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdfromat = new SimpleDateFormat("hh:ss | dd/ MM / yyyy");
String strDate = mdfromat.format(calendar.getTime());
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.mipmap.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher))
.setColor(Color.RED)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVibrate(new long[]{10,10,10})
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(notificationDetails)
.setContentText(strDate)
.addAction(R.mipmap.ic_launcher,"send",notificationPendingIntent)
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
//builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Maps geofence transition types to their human-readable equivalents.
*
* #param transitionType A transition type constant defined in Geofence
* #return A String indicating the type of transition
*/
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return getString(R.string.geofence_transition_entered);
case Geofence.GEOFENCE_TRANSITION_EXIT:
return getString(R.string.geofence_transition_exited);
default:
return getString(R.string.unknown_geofence_transition);
}
}
}
listPageActivty Class:
public class listPageActivty extends AppCompatActivity {
ListView listView;
String[] ListElements = new String[]{"Android","PHP"};
String item = "one";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_page_activty);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.listView2);
Button addBtn = (Button) findViewById(R.id.addBtn);
final List<String> ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(listPageActivty.this,android.R.layout.simple_list_item_1,ListElementsArrayList);
listView.setAdapter(adapter);
Bundle bundleData = getIntent().getExtras();
if (bundleData == null){
return;
}
String intentItem = bundleData.getString("intentKey");
ListElementsArrayList.add(intentItem);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListElementsArrayList.add(item);
adapter.notifyDataSetChanged();
}
});
}
}
Any Help would be Greatly Appreciated, Thank you.
You have to change this :
Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
to this :
Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
this.startActivity(i);
I think you just left the startActivity()
And in the other Activity you get the value like this :
String GeoTransitionDetails = getIntent().getExtras().getString("intentKey");
You are nowhere starting listPageActivty activity
Replace
Intent i = new Intent(this, listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
with
Intent i = new Intent(getBaseContext(), listPageActivty.class);
i.putExtra("intentKey",geofenceTransitionDetails);
getApplication().startActivity(dialogIntent);
Related
I want to send an sms to all saved contact only by shaking the phone. But i don't know how to link the database of saved contact and the code of sendind sms. Please help me with that.
This is the code for sending an sms by shaking the phone :
public class SensorService extends Service {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
public SensorService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
// start the foreground service
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
#SuppressLint("MissingPermission")
#Override
public void onShake(int count) {
// check if the user has shacked
// the phone for 3 time in a row
if (count == 3) {
// vibrate the phone
vibrate();
// create FusedLocationProviderClient to get the user location
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
// register the listener
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
// method to vibrate the phone
public void vibrate() {
final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
VibrationEffect vibEff;
// Android Q and above have some predefined vibrating patterns
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK);
vibrator.cancel();
vibrator.vibrate(vibEff);
} else {
vibrator.vibrate(500);
}
}
// For Build versions higher than Android Oreo, we launch
// a foreground service in a different way. This is due to the newly
// implemented strict notification rules, which require us to identify
// our own notification channel in order to view them correctly.
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("You are protected.")
.setContentText("We are there for you")
// this is important, otherwise the notification will show the way
// you want i.e. it will show some default notification
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public void onDestroy() {
// create an Intent to call the Broadcast receiver
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
}
And this is the code for saving contact number :
public void storeInDB(View v) {
Toast.makeText(getApplicationContext(), "Sauvegarde commencée",Toast.LENGTH_LONG).show();
name = (EditText) this.findViewById(R.id.textView1);
number = (EditText) this.findViewById(R.id.textView2);
String str_name=name.getText().toString();
String str_number=number.getText().toString();
SQLiteDatabase db;
db=openOrCreateDatabase("NumDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS details(name VARCHAR,number VARCHAR);");
Cursor c=db.rawQuery("SELECT * FROM details", null);
if(c.getCount()<3)
{
db.execSQL("INSERT INTO details VALUES('"+str_name+"','"+str_number+"');");
Toast.makeText(getApplicationContext(), "Enregistré avec succès",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Nombre maximum limité atteint",Toast.LENGTH_SHORT).show();
}
db.close();
}
Honestly i dont' know if you can send SMS to a list of contacts.
If you read this documentation:
https://www.tutorialspoint.com/android/android_sending_sms.htm
you'll read that the APIs receive MAX a telephone number.
I think this implementation is also due to a protection that android creates for avoiding to send a lot of sms togheter.
Assuming you have saved 1500 contacts on your device, your APP have to send 1500 sms???
It's strange....
But of couse you can create a loop and send a SMS a time...
I suggest you to:
detected shake gesture
retrieve all contacts saved (https://www.jackrutorial.com/2018/06/how-to-get-contacts-in-android-display-into-listview.html)
send a sms a time.
Edit with an update at the bottom with the cause, but still no fix
I am trying to capture a notification and later replay it once I dismiss it. From what I've been able to figure out so far, I can capture a notification, but when I try create a new notification using NotificationManager.notify(), nothing happens. No errors, nothing. Is this even something I should be able to do?
Maybe I am not taking the right approach and someone can suggest a better approach. Like I stated above, I want to be able to know when a user receives a notification and to capture the notification in its entirety, so even when it's dismissed, I can restore it. Maybe there is a way to restore things from the notification history but I haven't been able to figure out fully how that works yet. Here's the code I have so far. I can successfully listen to when a notification is posted or removed. The goal is to send a broadcast when a notification is posted with the notification id and the actual Notification itself (this part works I think), and when the button is pressed, recreate the notification. When I press the button, nothing happens.
public class MainActivity extends AppCompatActivity {
private int notification_id = -1;
private Notification myNotify;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle extras = myNotify.extras;
String title = extras.getString("android.title");
String text = extras.getString("android.text");
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nManager.notify(notification_id, myNotify);
}
});
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("notification_restore");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
#Nullable
public void onReceive(Context context, Intent intent) {
// Here you have the received broadcast
// And if you added extras to the intent get them here too
// this needs some null checks
Bundle b = intent.getExtras();
notification_id = b.getInt("notification_id");
myNotify = b.getParcelable("notification");
}
}
}
public class MyNotificationListenerService extends NotificationListenerService {
private int notification_id;
private Notification myNotify;
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
//Ignore the notification
return;
}
notification_id = sbn.getId();
myNotify = sbn.getNotification();
Intent intent = new Intent("notification_restore");
Bundle b = new Bundle();
b.putInt("notification_id", notification_id);
b.putParcelable("notification", myNotify);
intent.putExtras(b);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
//Ignore the notification
return;
}
}
}
Edit:
So it looks like the reason my notification isn't showing up is because it complains about not finding a channel, even though the notification I am trying to replay has one. The exact error is:
E/NotificationService: No Channel found for pkg=com.gevdev.notify, channelId=bugle_default_channel, id=0, tag=null, opPkg=com.gevdev.notify, callingUid=10086, userId=0, incomingUserId=0, notificationUid=10086, notification=Notification(channel=bugle_default_channel pri=1 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x10 color=0xff2a56c6 category=msg groupKey=bugle_notification_group_key sortKey=00 actions=2 vis=PRIVATE)
I am still new to android, but my initial guess is that the channelId found bugle_default_channel isn't found under my package name, but I don't know how to fix this yet.
Figured it out
Even though the notification that I am grabbing to replay has a channel ID, the NotificationManager doesn't have that notification channel registered. I figured it based off the code found here. This is how to register it.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = nManager.getNotificationChannel(myNotify.getChannelId());
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(myNotify.getChannelId(), "Description Goes Here", importance);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(true);
nManager.createNotificationChannel(notificationChannel);\
}
}
I've been using the Google Location Services API with Geofences. I can successfully catch Geofence transitions and I receive notifications when I enter and exit Geofences. However, I do not know how to make a Geofence transition make GUI and Data changes to the app.
For an example, if the app is open, I want a small toast to appear. I also need my app to generate a new geofence and discard the old one (but so far I'm only using a set of hardcoded geofences).
But so far, I do not understand how I can interact with my app from the GeofenceTransitionsEventService.java (which is where I "catch" the intents and create the notifications).
Below is my code (now edited, but still not working):
GPS Activity
public class GPSActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<Status> {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String mLastUpdateTime;
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private final int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;
private boolean locationPermissionGoodToGo = false;
public double latitude, longitude = 50;
protected static final String TAG = "MainActivity";
/**
* The list of geofences used in this sample.
*/
protected ArrayList<Geofence> mGeofenceList;
/**
* Used to keep track of whether geofences were added.
*/
private boolean mGeofencesAdded;
/**
* Used when requesting to add or remove geofences.
*/
private PendingIntent mGeofencePendingIntent;
/**
* Used to persist application state about whether geofences were added.
*/
private SharedPreferences mSharedPreferences;
// Buttons for kicking off the process of adding or removing geofences.
private Button mAddGeofencesButton;
private Button mRemoveGeofencesButton;
protected ResultReceiver mResultReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));
// Get the UI widgets.
mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button);
// Empty list for storing geofences.
mGeofenceList = new ArrayList<Geofence>();
// Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
mGeofencePendingIntent = null;
// Retrieve an instance of the SharedPreferences object.
mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME,
MODE_PRIVATE);
// Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default.
mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false);
setButtonsEnabledState();
// Get the geofences used. Geofence data is hard coded in this sample.
populateGeofenceList();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
initReceiver();
}
public void initReceiver(){
mResultReceiver = new AddressResultReceiver(new Handler()) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Check result code and/or resultData and take necessary action
if(resultCode == 0){
makeToast(resultData.getString("FROM_GEOFENCE_KEY"));
mRemoveGeofencesButton.setText("Remove TESTT");
}
}
};
// if(mResultReceiver != null){
// mAddGeofencesButton.setText("Add Geofences NOT NULL TEST");
//}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
}
public void makeToast(String string){
Toast.makeText(this, string, Toast.LENGTH_LONG).show();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_ACCESS_FINE_LOCATION);
}
// setCoordinates();
else{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
mLongitudeTextView.setText(String.valueOf(location.getLongitude()));
latitude = location.getLatitude();
longitude = location.getLongitude();
// Toast.makeText(this, "Updated: " + mLastUpdateTime, Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
locationPermissionGoodToGo = true;
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
//setCoordinates();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
locationPermissionGoodToGo = false;
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void startGame(){
//mGeofenceList.add(new Geofence.Builder()
Geofence fence = new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this geofence.
.setRequestId("hej")
.setCircularRegion(latitude, longitude, 150) //radius in meters
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.build();//;
}
/**
* Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored.
* Also specifies how the geofence notifications are initially triggered.
*/
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
// The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
// GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
// is already inside that geofence.
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
// Add the geofences to be monitored by geofencing service.
builder.addGeofences(mGeofenceList);
// Return a GeofencingRequest.
return builder.build();
}
/**
* Adds geofences, which sets alerts to be notified when the device enters or exits one of the
* specified geofences. Handles the success or failure results returned by addGeofences().
*/
public void addGeofencesButtonHandler(View view) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
}
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
// The GeofenceRequest object.
getGeofencingRequest(),
// A pending intent that that is reused when calling removeGeofences(). This
// pending intent is used to generate an intent when a matched geofence
// transition is observed.
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
logSecurityException(securityException);
}
}
/**
* Removes geofences, which stops further notifications when the device enters or exits
* previously registered geofences.
*/
public void removeGeofencesButtonHandler(View view) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
}
try {
// Remove geofences.
LocationServices.GeofencingApi.removeGeofences(
mGoogleApiClient,
// This is the same pending intent that was used in addGeofences().
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
logSecurityException(securityException);
}
}
private void logSecurityException(SecurityException securityException) {
Log.e(TAG, "Invalid location permission. " +
"You need to use ACCESS_FINE_LOCATION with geofences", securityException);
}
/**
* Runs when the result of calling addGeofences() and removeGeofences() becomes available.
* Either method can complete successfully or with an error.
*
* Since this activity implements the {#link ResultCallback} interface, we are required to
* define this method.
*
* #param status The Status returned through a PendingIntent when addGeofences() or
* removeGeofences() get called.
*/
public void onResult(Status status) {
if (status.isSuccess()) {
// Update state and save in shared preferences.
mGeofencesAdded = !mGeofencesAdded;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded);
editor.apply();
// Update the UI. Adding geofences enables the Remove Geofences button, and removing
// geofences enables the Add Geofences button.
setButtonsEnabledState();
Toast.makeText(
this,
getString(mGeofencesAdded ? R.string.geofences_added :
R.string.geofences_removed),
Toast.LENGTH_SHORT
).show();
} else {
// Get the status code for the error and log it using a user-friendly message.
String errorMessage = GeofenceErrorMessages.getErrorString(this,
status.getStatusCode());
Log.e(TAG, errorMessage);
}
}
/**
* Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
* issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
* current list of geofences.
*
* #return A PendingIntent for the IntentService that handles geofence transitions.
*/
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
//DESTROYS EVERYTHING---> intent.putExtra("RECEIVER_KEY", mResultReceiver);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
/**
* This sample hard codes geofence data. A real app might dynamically create geofences based on
* the user's location.
*/
public void populateGeofenceList() {
for (Map.Entry<String, LatLng> entry : Constants.BAY_AREA_LANDMARKS.entrySet()) {
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
// Set the circular region of this geofence.
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
// Set the expiration duration of the geofence. This geofence gets automatically
// removed after this period of time.
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
// Set the transition types of interest. Alerts are only generated for these
// transition. We track entry and exit transitions in this sample.
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
// Create the geofence.
.build());
}
}
/**
* Ensures that only one button is enabled at any time. The Add Geofences button is enabled
* if the user hasn't yet added geofences. The Remove Geofences button is enabled if the
* user has added geofences.
*/
private void setButtonsEnabledState() {
if (mGeofencesAdded) {
mAddGeofencesButton.setEnabled(false);
mRemoveGeofencesButton.setEnabled(true);
} else {
mAddGeofencesButton.setEnabled(true);
mRemoveGeofencesButton.setEnabled(false);
}
}
}
GeofenceTransisitionsIntentService
public class GeofenceTransitionsIntentService extends IntentService {
protected static final String TAG = "GeofenceTransitionsIS";
private ResultReceiver mResultReceiver;
/**
* This constructor is required, and calls the super IntentService(String)
* constructor with the name for a worker thread.
*/
public GeofenceTransitionsIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
}
#Override
public void onCreate() {
super.onCreate();
//Intent i = getIntent();
}
/**
* Handles incoming intents.
* #param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
#Override
protected void onHandleIntent(Intent intent) {
mResultReceiver = intent.getParcelableExtra(Constants.RECEIVER);
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
sendToActivity("Sending to activity test");
//Toast.makeText(this, geofenceTransitionDetails, Toast.LENGTH_SHORT).show();
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, "R.string.geofence_transition_invalid_type");
}
}
/**
* Gets transition details and returns them as a formatted string.
*
* #param context The app context.
* #param geofenceTransition The ID of the geofence transition.
* #param triggeringGeofences The geofence(s) triggered.
* #return The transition details formatted as String.
*/
private String getGeofenceTransitionDetails(
Context context,
int geofenceTransition,
List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList triggeringGeofencesIdsList = new ArrayList();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
private void sendNotification(String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), GPSActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(GPSActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Maps geofence transition types to their human-readable equivalents.
*
* #param transitionType A transition type constant defined in Geofence
* #return A String indicating the type of transition
*/
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return getString(R.string.geofence_transition_entered);
case Geofence.GEOFENCE_TRANSITION_EXIT:
return getString(R.string.geofence_transition_exited);
default:
return getString(R.string.unknown_geofence_transition);
}
}
public void sendToActivity(String string){
Bundle b=new Bundle();
b.putString("FROM_GEOFENCE_KEY", string);
mResultReceiver.send(0, b);
}
}
Here is my current error message which causes the app to crash
04-11 17:21:21.952 9528-9528/blueinteraction.mamn01blueinteraction W/System: ClassLoader referenced unknown path: /data/app/blueinteraction.mamn01blueinteraction-1/lib/arm
04-11 17:21:21.974 9528-9528/blueinteraction.mamn01blueinteraction I/GMPM: App measurement is starting up, version: 8487
04-11 17:21:21.974 9528-9528/blueinteraction.mamn01blueinteraction I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
04-11 17:21:21.983 9528-9528/blueinteraction.mamn01blueinteraction E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
04-11 17:21:21.984 9528-9528/blueinteraction.mamn01blueinteraction E/GMPM: Scheduler not set. Not logging error/warn.
04-11 17:21:22.008 9528-9528/blueinteraction.mamn01blueinteraction I/InstantRun: Starting server socket listening for package blueinteraction.mamn01blueinteraction on android.net.LocalSocketAddress#e9aec24
04-11 17:21:22.010 9528-9528/blueinteraction.mamn01blueinteraction I/InstantRun: Started server for package blueinteraction.mamn01blueinteraction
04-11 17:21:22.012 9528-9567/blueinteraction.mamn01blueinteraction E/GMPM: Uploading is not possible. App measurement disabled
04-11 17:21:22.138 9528-9572/blueinteraction.mamn01blueinteraction D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-11 17:21:22.196 9528-9572/blueinteraction.mamn01blueinteraction I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
04-11 17:21:22.199 9528-9572/blueinteraction.mamn01blueinteraction I/OpenGLRenderer: Initialized EGL, version 1.4
04-11 17:21:23.868 9528-9572/blueinteraction.mamn01blueinteraction D/OpenGLRenderer: endAllStagingAnimators on 0xb40e3280 (RippleDrawable) with handle 0x9f7bf6f0
04-11 17:21:29.767 9528-9572/blueinteraction.mamn01blueinteraction V/RenderScript: 0xaeca2000 Launching thread(s), CPUs 4
04-11 17:21:29.793 9528-9769/blueinteraction.mamn01blueinteraction E/AndroidRuntime: FATAL EXCEPTION: IntentService[GeofenceTransitionsIS]
Process: blueinteraction.mamn01blueinteraction, PID: 9528
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.ResultReceiver.send(int, android.os.Bundle)' on a null object reference
at blueinteraction.mamn01blueinteraction.GeofenceTransitionsIntentService.sendToActivity(GeofenceTransitionsIntentService.java:187)
at blueinteraction.mamn01blueinteraction.GeofenceTransitionsIntentService.onHandleIntent(GeofenceTransitionsIntentService.java:87)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
04-11 17:21:29.898 9528-9572/blueinteraction.mamn01blueinteraction D/OpenGLRenderer: endAllStagingAnimators on 0x9eee6280 (RippleDrawable) with handle 0x9f7bf670
I think these are the only classes I need to show you here for you to be able to help. Otherwise tell me what else to include.
You can use ResultReceiver to send data back to Activity or Fragment
https://developer.android.com/reference/android/os/ResultReceiver.html
its send method would allow to add resultCode and Bundle to send data back to class which implemented the receiver.
From your Activity or Fragment, you will pass an instance of receiver to the IntentService. Such as,
Intent intent = new Intent(context, GeofenceTransitionsIntentService.class);
intent.putExtra(Constants.RECEIVER, receiver);
activity.startService(intent);
Now in your IntentService class, you would get the receiver via bungle arguments and keep an instance in the class.
In your IntentService's onHandleIntent method, probably any where else you want to trigger the event, you will use the receiver to send the data back to the calling class. Something like this,
protected void onHandleIntent(Intent intent) {
ResultReceiver resultReceiver = intent.getParcelableExtra(Constants.RECEIVER);
}
ResultReceiver is Generic interface for receiving a callback result from someone. Use this by creating a subclass and implement onReceiveResult(int, Bundle), which you can then pass to others and send through IPC, and receive results they supply with send(int, Bundle).
So extend that class and create a new class in your app like this,
public abstract class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
}
Then AddressResultReceiver might look something like this in your Activity,
protected AddressResultReceiver mResultReceiver = new AddressResultReceiver(new Handler()) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Check result code and/or resultData and take necessary action
}
};
I hope this helps.
Ive added all the necessary code from the google documentation for implementing Geofencing in android. Although I can more or less understand what is going on, im trying to make the process as minimal as possible. Ideally, the user would pick a location and a geofence gets set around it. Once user enters the area, it should trigger an action. For now I am just trying to hard-code a location and get that working then take it from there. With that being said the button stuff is probably not necessary or the array-list of specified events.
My question is what is the bare minimum code I need to implement this process and what is the best way to go about it? This is my first android app so go easy on the heckling.
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Kick off the request to build GoogleApiClient.
buildGoogleApiClient();
mGeofencePendingIntent = null;
// Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default.
mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false);
// Get the geofences used. Geofence data is hard coded in this sample.
populateGeofenceList();
getGeofencePendingIntent();
getGeofencingRequest();
addGeofencesButtonHandler(this);
//Get the UI widgets.
mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button);
mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME,
MODE_PRIVATE);
}
}
#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 onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
myLat = lat;
myLng = lng;
mapCenter = new LatLng(myLat, myLng);
mMap.moveCamera(CameraUpdateFactory.newLatLng(mapCenter));
}
/**
* Builds a GoogleApiClient. Uses the {#code #addApi} method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void setUpMap() {
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get the name of the best provider
String networkProvider = locationManager.NETWORK_PROVIDER;
String gpsProvider = locationManager.GPS_PROVIDER;
// Get Best Current Location
myLocation = locationManager.getLastKnownLocation(networkProvider);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
//Add Marker For event
Intent myIntent = getIntent();
String desc = myIntent.getStringExtra("desc");
String addr = myIntent.getStringExtra("addr");
venueLat = myIntent.getDoubleExtra("lat", 0.0);
venueLng = myIntent.getDoubleExtra("lon", 0.0);
mMap.addMarker(new MarkerOptions().position(new LatLng(venueLat, venueLng)).title(desc).snippet(addr));
}
}
/*
*
*
*
*
* Geofence Stuff
*
*
*
*
*/
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
/**
* This sample hard codes geofence data. A real app might dynamically create geofences based on
* the users location.
*/
public void populateGeofenceList() {
for (Map.Entry<String, LatLng> entry : Constants.BAY_AREA_LANDMARKS.entrySet()) {
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
// Set the circular region of this geofence.
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
// Set the expiration duration of the geofence. This geofence gets automatically
// removed after this period of time.
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
// Set the transition types of interest. Alerts are only generated for these
// transition. We track entry and exit transitions in this sample.
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
// Create the geofence.
.build());
}
}
public void addGeofencesButtonHandler(View view) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
}
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
// The GeofenceRequest object.
getGeofencingRequest(),
// A pending intent that that is reused when calling removeGeofences(). This
// pending intent is used to generate an intent when a matched geofence
// transition is observed.
getGeofencePendingIntent()
).setResultCallback((ResultCallback<Status>) this); // Result processed in onResult().
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
// logSecurityException(securityException);
}
}
/**
* Runs when the result of calling addGeofences() and removeGeofences() becomes available.
* Either method can complete successfully or with an error.
*
* Since this activity implements the {#link ResultCallback} interface, we are required to
* define this method.
*
* #param status The Status returned through a PendingIntent when addGeofences() or
* removeGeofences() get called.
*/
public void onResult(Status status) {
if (status.isSuccess()) {
// Update state and save in shared preferences.
mGeofencesAdded = !mGeofencesAdded;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded);
editor.commit();
// Update the UI. Adding geofences enables the Remove Geofences button, and removing
// geofences enables the Add Geofences button.
setButtonsEnabledState();
Toast.makeText(
this,
getString(mGeofencesAdded ? R.string.geofences_added :
R.string.geofences_removed),
Toast.LENGTH_SHORT
).show();
} else {
// Get the status code for the error and log it using a user-friendly message.
String errorMessage = GeofenceErrorMessages.getErrorString(this,
status.getStatusCode());
Log.e(TAG, errorMessage);
}
}
/**
* Ensures that only one button is enabled at any time. The Add Geofences button is enabled
* if the user hasnt yet added geofences. The Remove Geofences button is enabled if the
* user has added geofences.
*/
private void setButtonsEnabledState() {
if (mGeofencesAdded) {
mAddGeofencesButton.setEnabled(false);
mRemoveGeofencesButton.setEnabled(true);
} else {
mAddGeofencesButton.setEnabled(true);
mRemoveGeofencesButton.setEnabled(false);
}
}
}
/*
* ---------------------------------------------------------------------------------------
*/
public class GeofenceTransitionsIntentService extends IntentService {
protected static final String TAG = "geofence-transitions-service";
/**
* This constructor is required, and calls the super IntentService(String)
* constructor with the name for a worker thread.
*/
public GeofenceTransitionsIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
}
#Override
public void onCreate() {
super.onCreate();
}
/**
* Handles incoming intents.
* #param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
#Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
// Toast.makeText(getApplicationContext(), geofenceTransitionDetails, Toast.LENGTH_SHORT).show();
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
}
}
/**
* Gets transition details and returns them as a formatted string.
*
* #param context The app context.
* #param geofenceTransition The ID of the geofence transition.
* #param triggeringGeofences The geofence(s) triggered.
* #return The transition details formatted as String.
*/
private String getGeofenceTransitionDetails(
Context context,
int geofenceTransition,
List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList triggeringGeofencesIdsList = new ArrayList();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
private void sendNotification(String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), MapsActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MapsActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder thats compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Maps geofence transition types to their human-readable equivalents.
*
* #param transitionType A transition type constant defined in Geofence
* #return A String indicating the type of transition
*/
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return getString(R.string.geofence_transition_entered);
case Geofence.GEOFENCE_TRANSITION_EXIT:
return getString(R.string.geofence_transition_exited);
default:
return getString(R.string.unknown_geofence_transition);
}
}
}
/*
* --------------------------------------------------------------------------
*/
public class Constants {
private Constants() {
}
public static final String PACKAGE_NAME = "com.google.android.gms.location.Geofence";
public static final String SHARED_PREFERENCES_NAME = PACKAGE_NAME + ".SHARED_PREFERENCES_NAME";
public static final String GEOFENCES_ADDED_KEY = PACKAGE_NAME + ".GEOFENCES_ADDED_KEY";
/**
* Used to set an expiration time for a geofence. After this amount of time Location Services
* stops tracking the geofence.
*/
public static final long GEOFENCE_EXPIRATION_IN_HOURS = 12;
/**
* For this sample, geofences expire after twelve hours.
*/
public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS =
GEOFENCE_EXPIRATION_IN_HOURS * 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 1609; // 1 mile, 1.6 km
/**
* Map for storing information about airports in the San Francisco bay area.
*/
public static final HashMap<String, LatLng> BAY_AREA_LANDMARKS = new HashMap<String, LatLng>();
static {
BAY_AREA_LANDMARKS.put("Home", new LatLng(29.382798, -98.529470));
BAY_AREA_LANDMARKS.put("Other Home", new LatLng(29.472491,-98.571244));
}
}
Here are few suggestions regarding your code:
Try to make it more modular. Separate out the code in different files according to the functionality you are expecting them to support (eg, maps code can be separated from location etc).
Make sure your app has the latest version of Google Play Services and making use of the FusedLocationApi.
Make sure the geofence radius is altelast 100 meters. Else the enter exit code wont be triggered.
Add the necessary permissions in the manifest files such as ACCESS_FINE_LOCATION, BroadCastreceiver (if you are using) etc.
Please refer to the following tutorial for code implementation.
I'm creating a notification by extending an Activity and every time the notification appears, my app keeps launching. It doesn't launch to the same activity every time. Instead, it launches the last used activity in my app. My notification is being launched at a specific date/time through AlarmManager. How do I prevent my notification from launching my app? I need it to launch the app when the user taps on it (that part is working fine), but I don't want it to launch the app when the notification appears for the first time in the status bar. Here's my code for the notifications:
public class DisplayReminderNotification extends SherlockActivity {
private Context context = this;
//Grab a handle onto the database and store the name of the reminder.
protected RemindersDAO remindersDAO;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the notification ID.
int notifID = getIntent().getExtras().getInt("Reminder_Primary_Key");
String reminderName = getIntent().getExtras().getString("Reminder_Name");
//PendingIntent stores the Activity that should be launched when the user taps the notification.
Intent i = new Intent(this, ViewLocalRemindersDetail.class);
i.putExtra("NotifID", notifID - randomInt);
i.putExtra("notification_tap", true);
displayIntent = PendingIntent.getActivity(this, notifID, i, 0);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.launcher_icon, reminderName, System.currentTimeMillis());
CharSequence from = "Here's your reminder:";
CharSequence message = reminderName;
notif.setLatestEventInfo(this, from, message, displayIntent);
//Fire up the notification.
nm.notify(notifID, notif);
//Destroy the activity/notification.
finish();
}
}
How do I solve my problem?
I tried your code after some minor modification and it is working fine at my end. Following is the code, I just changed the activity to launch with my blank activities called MyActivity:
public class DisplayReminderNotification extends Activity {
private Context context = this;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the notification ID.
int notifID = 1234;
String reminderName = "reminder";
// PendingIntent stores the Activity that should be launched when the
// user taps the notification.
Intent i = new Intent(this, MainActivity.class);
i.putExtra("NotifID", 123);
i.putExtra("notification_tap", true);
PendingIntent displayIntent = PendingIntent.getActivity(this, notifID,
i, 0);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.ic_launcher,
reminderName, System.currentTimeMillis());
CharSequence from = "Here's your reminder:";
CharSequence message = reminderName;
notif.setLatestEventInfo(this, from, message, displayIntent);
// Fire up the notification.
nm.notify(notifID, notif);
// Destroy the activity/notification.
finish();
}
}
I made this as main launcher activity and whenever I launch this activity it only add the notification at the notification bar and it is not launching the application. I would suggest you to try this code is a separate sample app. May be the problem is at some other part of your code.