local Notification with an Alarm Schedulling in Xamarin.Android doesn't work well - notifications

Am trying to make an Alarm notify on a scheduled time from my Sqlite, but the Alarm notifies only when i launch the Application, why is this
Below is how am Implementing my Alarm class:
public class AlarmImplementation
{
public AlarmImplementation()
{
}
public async void MakeAlarm()
{
MedicationDatabase db = new MedicationDatabase();
//This method has the list of time in Sqlite
var alarm_list = db.GetAlarmList();
//Debug.WriteLine(" Time -- : "+ m.ToString());
var message = "Hello Its me new one ";
var title = "Diabetics App";
//looping time from Sqlite
foreach (var list in alarm_list)
{
var hour = Int32.Parse(list.Substring(0, 2));
var minute = Int32.Parse(list.Substring(3, 2));
Debug.WriteLine("Hour : " + hour + "\n");
Debug.WriteLine("Minute " + minute + "\n");
Intent myintent = new Intent(Xamarin.Forms.Forms.Context, typeof(AlarmReceiver));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
PendingIntent pendingintent = PendingIntent.GetBroadcast(Xamarin.Forms.Forms.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
// PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
AlarmManager alarmManager = Xamarin.Forms.Forms.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);
}
}
}
Now when you look at my code above , I get time from my Sqlite then
i wire it in the AlarmManager.
Then in the code below i think i call the MakeAlarm Method in the
MainActivity.
This is my MainActivity class:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
// ActionBar.Hide();
RequestWindowFeature(WindowFeatures.NoTitle);
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
//Xamarin.Forms.Init();
AlarmImplementation a = new AlarmImplementation();
Task startupWork = new Task(() => { a.MakeAlarm(); });
startupWork.Start();
LoadApplication(new App());
}
}
My Question is how can i make an Alarm notify on a scheduled time
without pressing a Button, since i have my time in the Sqlite.

Related

Push notification after successful payment for mobile apps

I need help how to send push notifications on successful payment with transaction I'd to user
Use one of the background workers if you want to check the status of your transaction in background. I will use WorkManager.
implementation "android.arch.work:work-runtime:1.0.1"
public class SynchronizeWorker extends Worker {
static final String TAG = "MYWORKER";
public SynchronizeWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
private Notification getNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"WTF_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("WTF_CHANNEL_DESCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
// specify the class of the activity you want to open after click on notification
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
intent,
0);
return new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getApplicationContext().getResources().getString(R.string.notification_header))
.setContentText(getApplicationContext().getResources().getString(R.string.notification_text))
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.build();
}
#NonNull
#Override
public Result doWork() {
Log.d(TAG, "status checking started");
// check your transaction status here and show notification
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Log.d(TAG, "status checking finished");
}
Log.d(TAG, "status checking finished");
NotificationManagerCompat
.from(getApplicationContext())
.notify((int)(Math.random() * 10), getNotification());
return Result.success();
}
}
And then enqueue worker where you want to check status
OneTimeWorkRequest myWorkRequest = new OneTimeWorkRequest.Builder(SynchronizeWorker.class).build();
WorkManager.getInstance().enqueue(myWorkRequest);
I understand that it is probably not exactly what you want, but hope it will help somehow:)

Implement Infinite scroll with ViewModel And Retrofit in recyclerview

Before adding viewmodel & livedata , i successfully implemented infinity scroll with retrofit. But after adding viewmodel & livedata with Retrofit, My can't update recyclerview with new data call or viewmodel observer not update the list.
I simply want to infinite scrolling as my code does before. I add a global variable to reuse next page token. Am i missing anything or any sample to implement infinite recyclerview with viewmodel & retrofit will be awesome.
public static String NEXT_PAGE_URL = null;
I coded like that.
My Activity -> PlaceListActivity
placeRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
LogMe.d(tag, "onScrollStateChanged:: " + "called");
// check scrolling started or not
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LogMe.d(tag, "onScrolled:: " + "called");
super.onScrolled(recyclerView, dx, dy);
currentItem = layoutManager.getChildCount();
totalItems = layoutManager.getItemCount();
scrolledOutItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
LogMe.d(tag, "currentItem:: " + currentItem);
LogMe.d(tag, "totalItems:: " + totalItems);
LogMe.d(tag, "scrolledOutItems:: " + scrolledOutItems);
if (isScrolling && (currentItem + scrolledOutItems == totalItems)) {
LogMe.d(tag, "view:: " + "finished");
isScrolling = false;
if (ApplicationData.NEXT_PAGE_URL != null) {
LogMe.d(tag, "place adding:: " + " onScrolled called");
ll_loading_more.setVisibility(View.VISIBLE);
// todo: call web api here
callDataFromLocationAPi(type, ApplicationData.NEXT_PAGE_URL, currentLatLng);
} else {
LogMe.d(tag, "next_page_url:: " + " is null");
}
}
}
});
private void callDataFromLocationAPi(String type, String next_page_url, LatLng latLng) {
if (Connectivity.isConnected(activity)) {
showProgressDialog();
model.getNearestPlaces(type, next_page_url, latLng).
observe(activity, new Observer<List<PlaceDetails>>() {
#Override
public void onChanged(#Nullable List<PlaceDetails> placeDetails) {
ll_loading_more.setVisibility(View.GONE);
LogMe.i(tag, "callDataFromLocationAPi: onChanged called !");
hideProgressDialog();
if (placeDetails != null) {
placeDetailsList = placeDetails;
placeListAdapter.setPlaceList(placeDetails);
}
}
});
} else {
showAlertForInternet(activity);
}
}
In PlaceViewModel
public class PlaceViewModel extends AndroidViewModel {
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
private PlaceRepository placeRepository;
private String tag = getClass().getName();
public PlaceViewModel(Application application) {
super(application);
placeRepository = new PlaceRepository(application);
}
//we will call this method to get the data
public MutableLiveData<List<PlaceDetails>> getNearestPlaces(String type,
String next_page_token,
LatLng latLng) {
//if the list is null
if (placeList == null) {
placeList = new MutableLiveData<>();
//we will load it asynchronously from server in this method
//loadPlaces(type, next_page_token, latLng);
placeList = placeRepository.getNearestPlacesFromAPI(type, next_page_token, latLng);
}
//finally we will return the list
return placeList;
}
}
In my PlaceRepository.java looks
public class PlaceRepository {
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// Since we didn't alter the table, there's nothing else to do here.
}
};
private PlaceDatabase placeDatabase;
private CurrentLocation currentLocation = null;
private String tag = getClass().getName();
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
public PlaceRepository(Context context) {
placeDatabase = PlaceDatabase.getDatabase(context);
//addMigrations(MIGRATION_1_2)
placeList =
new MutableLiveData<>();
}
public MutableLiveData<List<PlaceDetails>> getNearestPlacesFromAPI(String type, final String next_page_token, LatLng latLng) {
List<PlaceDetails> placeDetailsList = new ArrayList<>();
try {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiService.getNearbyPlaces(type,
latLng.latitude + "," +
latLng.longitude, ApplicationData.PROXIMITY_RADIUS,
ApplicationData.PLACE_API_KEY, next_page_token);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
try {
Example example = response.body();
ApplicationData.NEXT_PAGE_URL = example.getNextPageToken();
// next_page_url = example.getNextPageToken();
LogMe.i(tag, "next_page_url:" + ApplicationData.NEXT_PAGE_URL);
if (example.getStatus().equals("OK")) {
LogMe.i("getNearbyPlaces::", " --- " + response.toString() +
response.message() + response.body().toString());
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < example.getResults().size(); i++) {
Double lat = example.getResults().get(i).getGeometry().getLocation().getLat();
Double lng = example.getResults().get(i).getGeometry().getLocation().getLng();
String placeName = example.getResults().get(i).getName();
String vicinity = example.getResults().get(i).getVicinity();
String icon = example.getResults().get(i).getIcon();
String place_id = example.getResults().get(i).getPlaceId();
PlaceDetails placeDetails = new PlaceDetails();
if (example.getResults().get(i).getRating() != null) {
Double rating = example.getResults().get(i).getRating();
placeDetails.setRating(rating);
}
//List<Photo> photoReference = example.getResults().
// get(i).getPhotos();
placeDetails.setName(placeName);
placeDetails.setAddress(vicinity);
placeDetails.setLatitude(lat);
placeDetails.setLongitude(lng);
placeDetails.setIcon(icon);
placeDetails.setPlace_id(place_id);
//placeDetails.setPlace_type(place_type_title);
double value = ApplicationData.
DISTANCE_OF_TWO_LOCATION_IN_KM(latLng.latitude, latLng.longitude, lat, lng);
//new DecimalFormat("##.##").format(value);
placeDetails.setDistance(new DecimalFormat("##.##").format(value));
String ph = "";
if (example.getResults().
get(i).getPhotos() != null) {
try {
List<Photo> photos = example.getResults().
get(i).getPhotos();
//JSONArray array = new JSONArray(example.getResults().
//get(i).getPhotos());
//JSONObject jsonObj = new JSONObject(array.toString());
//ph = jsonObj.getString("photo_reference");
ph = photos.get(0).getPhotoReference();
//LogMe.i(tag, "\n" + ph);
} catch (Exception e) {
e.printStackTrace();
//placeDetails.setPicture_reference(ph);
//PLACE_DETAILS_LIST.add(placeDetails);
//LogMe.i(tag, "#### Exception Occureed ####");
ph = "";
//continue;
}
}
placeDetails.setPicture_reference(ph);
placeDetailsList.add(placeDetails);
placeList.postValue(placeDetailsList);
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.e("onFailure", t.toString());
}
});
} catch (RuntimeException e) {
//hideProgressDialog();
Log.d("onResponse", "RuntimeException is an error");
e.printStackTrace();
} catch (Exception e) {
Log.d("onResponse", "Exception is an error");
}
return placeList;
}
}
I precise code due to question simplicity.
Though you already use android-jetpack, take a look at Paging library. It's specially designed for building infinite lists using RecyclerView.
Based on your source code, I'd say that you need PageKeyedDataSource, here is some example which includes info about how to implement PageKeyedDataSource -
7 steps to implement Paging library in Android
If talking about cons of this approach:
You don't need anymore to observe list scrolling (library doing it for you), you just need to specify your page size in the next way:
PagedList.Config myPagingConfig = new PagedList.Config.Builder()
.setPageSize(50)
.build();
From documentation:
Page size: The number of items in each page.
Your code will be more clear, you'll get rid of your RecyclerView.OnScrollListener
ViewModel code will be shorter, it's will provide only PagedList:
#NonNull
LiveData<PagedList<ReviewSection>> getReviewsLiveData() {
return reviewsLiveData;
}

Notification "setSound()" in Android 8

Here's the question, the code of notification can't work with Android 8.
I can't set the notification sound myself. The only result it shows is the system sound "Bee".
Here's my code:
if(Build.VERSION.SDK_INT>=26) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "channel_1";
String description = "123";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, "123", importance);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setLightColor(Color.GREEN);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
AudioAttributes aa = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
mChannel.setSound(Uri.parse("android.resource://com.example.lenovo.projectmonitor/" + R.raw.video11),aa);
manager.createNotificationChannel(mChannel);
Notification notification = new NotificationCompat.Builder(NotificationService.this, "channel_1")
.setContentTitle("new alarm")
.setContentText(nameAll.get(0))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
manager.notify(1, notification);
}
use setSound method in both NotificationChannel and NotificationCompat.Builder class. example
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
channel.setSound(null, null);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
and creating buileder:
public void buildNotification(Class className, int smallIconId) {
createNotificationChannel();
// Create an Intent for the activity you want to start
Intent intent = new Intent(context, className);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
// TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// stackBuilder.addNextIntentWithParentStack(intent);
//// Get the PendingIntent containing the entire back stack
// PendingIntent pendingIntent =
// stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder
.setSmallIcon(smallIconId)
.setContentTitle("Recording Audio..")
// .setContentText("Much longer text that cannot fit one line...")
// .setStyle(new NotificationCompat.BigTextStyle()
// .bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(null)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
// notificationId is a unique int for each notification that you must define
// notificationManager.notify(notificationId, mBuilder.build());
// mBuilder.setContentTitle("changed it");
// notificationManager.notify(notificationId, mBuilder.build());
// mHandler.postDelayed(new Runnable() {
// #Override
// public void run() {
// }
// }, 3000);
}

Android: How to fix BroadcastReceiver in JobIntentService?

I have an Activity with an AlarmManager that fires a BroadcastReceiver. The BroadcastReceiver fires a JobIntentService to send a Notification to the user.
When the user taps "CLEAR ALL" or swipes to dismiss the Notification, I want the setDeleteIntent() to reset a counter variable "totalMessages" to zero that I set up in a SharedPreferences file. It is not resetting to zero. What am I missing here?
public class AlarmService extends JobIntentService {
static final int JOB_ID = 9999;
public static final String NOTIFICATIONS_COUNTER = "NotificationsCounter";
private static final int REQUEST_CODE_DELETE_INTENT = 1;
int totalMessages = 0;
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, AlarmService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
IntentFilter filter = new IntentFilter();
filter.addAction("notification_cleared");
registerReceiver(receiver, filter);
sendNotification();
}
private void sendNotification() {
int notifyID = 1;
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
SharedPreferences sp = getSharedPreferences(NOTIFICATIONS_COUNTER, Context.MODE_PRIVATE);
totalMessages = sp.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
SharedPreferences.Editor editor = sp.edit();
editor.putInt("total-messages", ++totalMessages);
editor.apply();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_announcement_white_24dp)
.setContentText("")
Intent i = new Intent(this, AlarmService.class);
i.setAction("notification_cleared");
PendingIntent deleteIntent = PendingIntent.getBroadcast(this,REQUEST_CODE_DELETE_INTENT,i,PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setDeleteIntent(deleteIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mBuilder.setSubText(String.valueOf(totalMessages));
}
else {
mBuilder.setNumber(totalMessages);
}
if (notificationManager != null) {
notificationManager.notify(notifyID, mBuilder.build());
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
if (action.equals("notification_cleared")) {
// Reset the Notifications counter ("total-messages") to zero since the user
// clicked on "CLEAR ALL" Notification or swiped to delete a Notification.
SharedPreferences sp1 = getSharedPreferences(NOTIFICATIONS_COUNTER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp1.edit();
editor.clear();
editor.apply();
totalMessages = sp1.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
editor.putInt("total-messages", totalMessages);
editor.apply();
}
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
The problem is that your broadcast receiver's implementation to clear notifications is within the life-cycle of job. JobIntentService is tasked to show notification and go away thus the broadcast receiver. But when the user clicks on the CLEAR from notification, the pending intent is broadcasted but then there's no one to listen to it.
For a solution, I would suggest you to create a separate broadcast receiver and register it in your AndroidManifest.xml. By then your broadcast will always be listened and you can perform what ever within..

ProximityAlert with a BroadcastReceiver not working

I am new to Android and have a problem with adding ProximityAlert with a BroadcastReceiver. I know that this topic has been taken up earlier as well but I am trying to add proximity alert to different locations and I am not sure if what I am trying to do is quite achievable this way or I am just doing it wrong.
Problem : I have tried to implement the code for adding ProximityAlert with a BroadcastReceiver, but its not working some how. Below is the snippet from my code (posted below) requesting all to please have a look and help me out with it.
I have this userLocations list. I am adding Proximity Alert to all the user mentioned location by running a for loop for the list. I only want to add a proximity Alert to the user location if that particular location has not been visited by the user before.
I then register the receiver in the addLocationProximity() method, which is called from the onResume() method. I unregisterReceiver the receiver in the onPause() method.
I have also used the onLocationChanged() method to populate a list (which I would be needing for later) based on the same logic which have been used to add the proximity alert.
Please do let me know if any of these steps have not been carried out correctly.
Thanks in advance.
package com.android.locationmang;
public class ViewAActivity extends ListActivity implements LocationListener{
private static final String PROX_ALERT_INTENT = "com.android.locationmang.PROX_ALERT_INTENT";
private static final long LOCAL_FILTER_DISTANCE = 1200;
public static List<UserLocation> notifiedLocationsList;
public static Location latestLocation;
PendingIntent pendingIntent;
Intent notificationIntent;
private LocationManager locationManager;
List<UserLocations> userLocations;
private IntentFilter filter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
notifiedLocationsList = new ArrayList<UserLocation>();
userLocations = getUserLocations(); //Returns a list of user Locations stored by the user on the DB
filter = new IntentFilter(PROX_ALERT_INTENT);
}
private void setUpLocation() {
locationNotificationReceiver = new LocationNotificationReceiver();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 5, this);
for (int i = 0; i < userLocation.size(); i++){
UserLocation userLocation = userLocation.get(i);
if(!(userLocation.isComplete())){
setProximityAlert(userLocation.getLatitude(),
userLocation.getLongitude(),
i+1,
i);
}
}
registerReceiver(locationNotificationReceiver, filter);
}
private void setProximityAlert(double lat, double lon, final long eventID, int requestCode){
// Expiration is 10 Minutes (10mins * 60secs * 1000milliSecs)
long expiration = 600000;
Intent intent = new Intent(this, LocationNotificationReceiver.class);
intent.putExtra(LocationNotificationReceiver.EVENT_ID_INTENT_EXTRA, eventID);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
locationManager.addProximityAlert(lat, lon, LOCAL_FILTER_DISTANCE, expiration, pendingIntent);
}
#Override
protected void onResume() {
super.onResume();
setUpLocation();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 5, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
unregisterReceiver(locationNotificationReceiver);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public boolean userLocationIsWithinGeofence(UserLocation userLocation, Location latestLocation, long localFilterDistance) {
float[] distanceArray = new float[1];
Location.distanceBetween(userLocation.getLatitude(), userLocation.getLongitude(), latestLocation.getLatitude(), latestLocation.getLongitude(), userLocation.getAssignedDate(),distanceArray);
return (distanceArray[0]<localFilterDistance);
}
public void onLocationChanged(Location location) {
if (location != null) {
latestLocation = location;
for (UserLocation userLocation : userLocations) {
if (!(userLocations.isVisited()) && userLocationIsWithinGeofence(userLocation, latestLocation, LOCAL_FILTER_DISTANCE)) {
notifiedLocationsList.add(userLocation);
}
}
}
}
}
Code for BroadcastReceiver
package com.android.locationmang;
public class LocationNotificationReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
public static final String EVENT_ID_INTENT_EXTRA = "EventIDIntentExtraKey";
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
long eventID = intent.getLongExtra(EVENT_ID_INTENT_EXTRA, -1);
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}
else{
Log.d(getClass().getSimpleName(), "exiting");
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
Intent notificationIntent = new Intent(context, MarkAsCompleteActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!", "You are near your point of interest.", pendingIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}
Thanks and Regards
You are creating a broadcast Intent with an action string, and your <receiver> element does not have the corresponding <intent-filter>. Change:
Intent intent = new Intent(PROX_ALERT_INTENT);
to:
Intent intent = new Intent(this, LocationNotificationReceiver.class);