Push notification after successful payment for mobile apps - notifications

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:)

Related

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..

Parse | Push Notification Straight Into Web View, How?

I've searched in the web, parse docs and ask many people but no one can point me how to do it.
I have an RSS app who getting the articles into a UITableView.
when I'm sending a Push it's open the app itself but not the article I want to (well obviously since I don't know how to code that) .
Can anyone please give me ideas how to do it ?
(code sample will be useful as well) .
First of all you have to implement your own Receiver class instead of default Parse push receiver and put it into AndroidManifest.xml as follows :
<receiver android:name="net.blabla.notification.PushNotifHandler" android:exported="false">
<intent-filter>
<action android:name="net.bla.PUSH_MESSAGE" />
</intent-filter>
</receiver>
In your PushNotifHandler.java class you should put some parameters to Intent you will throw as follows :
public class PushNotifHandler extends BroadcastReceiver{
private static final String TAG = PushNotifHandler.class.getSimpleName();
private static int nextNotifID = (int)(System.currentTimeMillis()/1000);
private static final long VIBRATION_DURATION = 500;
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
Intent resultIntent = new Intent(context, ToBeOpenedActivity.class);
JSONObject jsonData = new JSONObject(intent.getExtras().getString("com.parse.Data"));
fillNotificationData(jsonData, action, resultIntent);
String title = jsonData.getString("messageTitle") + "";
String message = jsonData.getString("messageText") + "";
TaskStackBuilder stackBuilder = TaskStackBuilder.from(context);
stackBuilder.addParentStack(ToBeOpenedActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).
setSmallIcon(R.drawable.icon).
setContentTitle(title).
setContentText(message).
setAutoCancel(true);
builder.setContentIntent(resultPendingIntent);
notification = builder.getNotification();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(TAG, nextNotifID++, notification);
vibratePhone(context);
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
private void vibratePhone(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATION_DURATION);
}
private void fillNotificationData(JSONObject json, String action, Intent resultIntent)
throws JSONException {
Log.d(TAG, "ACTION : " + action);
resultIntent.putExtra("paramString", json.getString("paramFromServer"));
}
}
With key "com.parse.Data" you will get parameters sent from your server code as json format.After getting paramString and paramBoolean parameters from this json, you will put these parameters into new Intent you hav created as seen in fillNotificationData method.
Other parts of onReceive method creates a local notification and vibrates the device.
Finally on your activity class onResume() method you will check intent parameters to realize if you are opening the app from push notification or not.
#Override
public void onResume() {
super.onResume();
checkPushNotificationCase(getIntent());
}
private void checkPushNotificationCase(Intent intent) {
Bundle extraParameters = intent.getExtras();
Log.d("checking push notifications intent extras : " + extraParameters);
if (extraParameters != null) {
if(extraParameters.containsKey("paramString")) {
// doSomething
}
}
}
I hope you have asked this question for Android :))

NotificationCompat.Builder and startForeground

This works: IntentService with NotificationCompat.Builder providing a notification to use with NotificationManager.notify() .setContentIntent(pendingIntent) is needed. When notify is sent, the notification appears in the notification AND IS PERSISTENT (stays alive until the user clicks it, at which point it starts the activity specified in .setContentIntent). Good!
What does not work: I would like the service to be long-lived like a phone-service, so startForeground() would seem advised. However, when I include that, the associated notification does indeed appear in the tray as it should, but it is NOT PERSISTENT and disappears when the IntentService ends (unlike above). (The associated notification also uses .setContentIntent and starts another Activity.)
Any thoughts? It is critical that the service not die until it detects a certain (rare) "event". It is also critical that the notification remains alive until the user responds by clicking it!
Here is the boiled-down code (latter case): Thanks!
public class SService extends IntentService {
public SService() {
super("SService");
}
#Override
protected void onHandleIntent(Intent sIntent) {
//Notification construction:
Notification notif;
Context context = this;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(context, BarNotifActivity.class);
PendingIntent pbIntent = PendingIntent.getActivity(context, 0, bIntent,0);
Notification barNotif;
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.bar_title))
.setContentText(getString(R.string.bar_text))
//.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
long[] vibration = {0, 300, 1000, 300, 1000, 300, 1000, 300, 1000};
Intent mIntent = new Intent(context, NotifReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, mIntent,0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.alert_text))
.setContentText(getString(R.string.alert_text))
.setTicker("**Notification Arrived!**")
.setVibrate(vibration)
//.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pIntent);
notif = mBuilder.build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_INSISTENT;
try {
Thread.sleep(7000); //Pause 7 sec.
} catch (InterruptedException e) {
e.printStackTrace();
}
mNotificationManager.notify(1, notif);
}
}

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);