Android Proximity Alerts Not Working - java

I'mm trying to create an app that allows you to set a proximity alert for marker when you click on it's info window.
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker marker) {
LatLng clickedMarkerLatLng = marker.getPosition();
double lat = clickedMarkerLatLng.latitude;
double long1 = clickedMarkerLatLng.longitude;
Log.e("hello", "Output=" + lat + long1);
LocationManager lm;
// double lat=123,long1=34; //Defining Latitude & Longitude
float radius=30; //Defining Radius
lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Intent i= new Intent("com.example.sleepertrain5.ProximityReceiver"); //Custom Action
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, i, PendingIntent.FLAG_CANCEL_CURRENT);
lm.addProximityAlert(lat, long1, radius, -1, pendingIntent);
}
This is the code that calls the Broadcast Receiver
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();
}
}
The above is the Broadcast receiver. None of this works and I can't figure out why. Any help would be great.

Use below code for Pending Intent:
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
nId, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Where nId will be any uniq number that represent particular pending intent.

Related

How can I pass data from an Activity to a Geofence BroadcastReceiver?

I was building a Geofencing Application to track the number of people in the given region at any given time and storing their IDs on a Backend.
I am unable to figure out how to pass the ID I take from the user and to the GeofenceBroadcastReceiver where I am incrementing and decrementing the number of people in the onReceive so I can keep a track of who all are in there.
I don't think it can be passed through an intent as I am not the one calling the Receiver and I am unfamiliar of the inner workings of the process.
MainActivity.java
public void addGeofence(LatLng latLng, float radius) {
Geofence geofence = geofenceHelper.getGeofence(GEOFENCE_ID, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_EXIT);
GeofencingRequest geofencingRequest = geofenceHelper.getGeofencingRequest(geofence);
PendingIntent pendingIntent = geofenceHelper.getPendingIntent();
geofencingClient.addGeofences(geofencingRequest, pendingIntent).addOnSuccessListener(
\\code );
GeofenceHelper.java
public class GeofenceHelper extends ContextWrapper {
PendingIntent pendingIntent;
public GeofenceHelper(Context base) {
super(base);
}
public GeofencingRequest getGeofencingRequest(Geofence geofence) {
return new GeofencingRequest.Builder()
.addGeofence(geofence)
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.build();
}
public Geofence getGeofence(String ID, LatLng latLng, float radius, int transitionTypes) {
return new Geofence.Builder()
.setCircularRegion(latLng.latitude, latLng.longitude, radius)
.setRequestId(ID)
.setTransitionTypes(transitionTypes)
.setLoiteringDelay(5000)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
}
public PendingIntent getPendingIntent() {
if (pendingIntent != null) {
return pendingIntent;
}
Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
No need to pass data from activity to GeofenceBroadcastReceiver. When user enters geofence area, GeofenceBroadcastReceiver onReceive() automatically will be called by android system if you properly registered geofence.
First register your geofence once added successfully, in your emulator set your registered geofence location and move around to trigger enter and exit of geofence. When triggered, onReceive() automatically will be called and you can get triggered id from onReceive() intent. Then you can increment and decrement number of people with in onReceive()

Open google map from notification via intent

I have an BroadcastReciver that listens for incoming sms. When sms come, it shows notification. I want, when user open notification, it's go to result activity, and it's open google map via intent.
I think I wrote everything ok, but it doesn't work. When the notification is clicked, it opens a blank page.
My incomingSms BroadcastReciver :
public void ShowNotif(String from , String body , Context con){
NotificationCompat.Builder builder =
new NotificationCompat.Builder(con)
.setSmallIcon(R.drawable.ic_search)
.setContentTitle(from)
.setContentText(body);
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(con,Resualt.class );
targetIntent.putExtra("loc",body);
PendingIntent contentIntent = PendingIntent.getActivity(con, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) con.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
Intent goResIntent = new Intent(con , Resualt.class);
con.startActivity(goResIntent);
// gogole map intent :
}
and Resualt acitivty :
public class Resualt extends Activity {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.resualt);
double Mylatitude = 12;
double Mylongitude = 11;
GPSTracker tracker = new GPSTracker(this);
if (tracker.canGetLocation()) {
Mylatitude = tracker.getLatitude();
Mylongitude = tracker.getLongitude();
}
Intent intent = getIntent();
String location = intent.getStringExtra("loc");
String ACC_lat = location.substring(0, location.indexOf(","));
String ACC_lang = location.substring(location.indexOf(",") + 1, location.length());
Toast.makeText(this, ACC_lang + " ^ " + ACC_lat, Toast.LENGTH_LONG).show();
Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+Mylatitude +","+ Mylongitude+"&daddr="+ACC_lat+","+ACC_lang));
startActivity(mapIntent);
// this.finish();
}
thanks for any help .
You can open a single blank activity through pending intent in notification service and then on that blank activity open a map intent and finish that blank activity.
the link receiving from notification data can be sent through intent as extras
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("location_link", link);

Getting Android Alarms Info

Iv'e created several Alarms using an Intent and BroadcastReciever and placed them in an Array of Intents.
For each Intent Iv'e placed a String as in Intent.PutExtra("info", string); to be shown later as a Toast when Alarm is activated,
and gave each a different requestCode.
But when adding multiple Alarms, the Toast shows EVERY other Alarms' info as well.
MainActivity:
Intent newAlarmIntent = new Intent(this,AlarmReceiver.class);
newAlarmIntent.putExtra("info",editText.getText().toString());
alarmsArray[alarmCounter]=newAlarmIntent;
alarm.AlarmListSortAndSetNext(gameArrayList, alarmArray, this,alarmCounter,alarmsArray[alarmCounter]);
Alarm Class:
public void CreateNew (Context context, Long alarmTimeAsLong, int counter, Intent intent)
{
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getBroadcast(context, counter, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager;
manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, (alarmTimeAsLong),pendingIntent);
Toast.makeText(context, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void AlarmListSortAndSetNext (ArrayList<Game> gameArrayList,Long[] alarmArray,Context context,int alarmCounter, Intent intent)
{
Long SystemTimeAsLong = System.currentTimeMillis();
//Sorting Long Array for NEXT ALARM
for (int i=0;i<10;i++)
{if(i<gameArrayList.size()){
alarmArray[i] = gameArrayList.get(i).getDateAndTimeAsLong();
}
else alarmArray[i]= 0L;
}
Arrays.sort(alarmArray);
//Setting next ALARM by Long Size
for(int i=0;i<10;i++)
{
if (alarmArray[i]>SystemTimeAsLong){
CreateNew(context,alarmArray[i],alarmCounter,intent);
alarmCounter++;}
}}
AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
String gameInfo= intent.getStringExtra("info");
Toast.makeText(context, gameInfo, Toast.LENGTH_SHORT).show();
MediaPlayer mp = MediaPlayer.create(context, R.raw.bipbip);
mp.start();
wakeLock.release();}}
QUESTION: How can I make each Intent to have it's on "info"/PutExtra, or any other way to tell which one has been activate?
* Found the issue *
I had left the AlarmListSortAndSetNext method which initially was supposed to manage the Next Alarm. I no longer have to use this method since I have created multiple Intents. Something in the looping probably created multiple putExtra();
Thank you.

Android Status Bar Notification is not updating when app is closed

I have an app which shows battery charge and temperature in the status bar and notification bar. When the app is opened I can see the data updates in the status bar and notification. When I exit/close the app the status bar and notification is not updating its values. Why is the status bar and notification bar not updating when I close the app?
I use BroadcastReceiver to display the notification.
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
notificationMessage(context, intent);
}
private void notificationMessage(Context context, Intent intent){
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
int icon = R.drawable.battery_level_images;
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
float cTemperature = (float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)/10;
float fTemperature = celsiusToFahrenheit(cTemperature);
float voltage = (float) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)/1000;
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
String healthText = getHealthText(health);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("" + level + "% | " + healthText)
.setContentText(cTemperature + "\u2103 | " + fTemperature + "\u2109 | " + voltage + "V")
.setSmallIcon(icon, level)
.setWhen(0)
.setProgress(100, level, false)
.setOngoing(true)
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(0, notification);
}
In my main activity class I turn on the notification with a checkbox.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
............................
myReceiver = new MyReceiver();
ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatus = this.registerReceiver(mBatteryInfoReceiver, ifilter);
....................
}
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((CheckBox) view).isChecked();
if (on) {
batteryStatus = this.registerReceiver(myReceiver, ifilter);
SavingData.setNotificationState(true);
} else {
try{
this.unregisterReceiver(myReceiver);
}catch (IllegalArgumentException iae){
iae.printStackTrace();
}
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
SavingData.setNotificationState(false);
}
}
Here is my BroadcastReceiver in my AndroidManifest.
<receiver android:name=".MyReceiver" />
Register your BroadcastReceiver in your service and run it in your background. Running your service all the time might drain users battery. Beware :)
Once your activity is destroyed, your BroadcastReceiver registered via registerReceiver() will go away as well. You probably have a warning or error in LogCat pointing this out to you. Once your BroadcastReceiver is gone, you will stop updating the Notification.

Proximity Alert Class Doesn't Fire Android

I'm trying to set up a proximity alarm based on the location of a selected marker, the coordinates for which are stored in an external file and read into an array, which in turn draws the coordinates.
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker marker) {
LatLng clickedMarkerLatLng = marker.getPosition();
double lat = clickedMarkerLatLng.latitude;
double long1 = clickedMarkerLatLng.longitude;
Log.e("hello", "Output=" + lat + long1);
LocationManager lm;
// double lat=0;
// double long1=0; //Defining Latitude & Longitude
float radius=3000;
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
Intent i= new Intent("com.example.sleepertrain5.proximityalert"); //Custom Action
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), -1, i, 0);
lm.addProximityAlert(lat, long1, radius, -1, pi);
Toast.makeText(getBaseContext(),
"Info Window clicked#" + lat + "dddjdj" + long1,
Toast.LENGTH_SHORT).show();
class ProximityReceiver extends android.content.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();
}
}
}
}
});
}
The coordinates of the selected marker are passed to the location manager, but the proximity alarm doesn't work. Obviously at the moment, it just displays a toast, but it's not even doing that. According to the Log, the Proximity receiver class is never called, but I can't figure out why. I've tried it with varying sizes of radius and it still doesn't work. Any ideas or help?
You need to register your BroadcastReceiver with the Intents action you used for the PendingIntent. You can do this in the AndroidManifest.xml by adding these lines:
<receiver android:name="MyScheduleReceiver" >
<intent-filter>
<action android:name="com.example.sleepertrain5.proximityalert" />
</intent-filter>
</receiver>

Categories

Resources