I want to cancel/delete the notification after I click the addAction.
However it's not working. The notification is still there after the click.
I'm pretty sure this worked in an other project.
Can anyone see a stupid error I made, why its not working?
Actual code:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context){
String onderwerp = ("Medicatietijd");
String name = ("Het is tijd om je medicitie in te nemen.");
// Geluid notificatie
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Test.class), 0);
// De notificatie
Notification mNotification = new Notification.Builder(context)
.setContentTitle(onderwerp)
.setContentText(name)
.setSmallIcon(R.drawable.ninja)
.setSound(soundUri)
.addAction(R.drawable.ja, "Ja, ik heb ze ingenomen.", contentIntent)
.setAutoCancel(true)
.build();
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification.vibrate = new long[]{100, 200, 100, 500};
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
Solution:
In test activity OnCreate added this:
NotificationManager notificationManager
= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
If you decided to use Test activity to receive the intent of your addAction call, then you must cancel notification when you receive the intent in the activity.
I also recommend that you add requestCode for the intent.
Here is the code :
to set the requestCode modify this :
static final int REQ_CODE = 101; // some number
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, REQ_CODE,
new Intent(context, Test.class), 0);
to Handle intent in activity and dismiss the notification, in Test activity class :
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_CODE) {
// dismiss notification
notificationManager.cancel(0);
// handle your action
// ...
}
}
Hope that helps
Related
How can I open an activity on the lock screen without the user having to click on it? Like for example an alarm or a call.
In my code I can get the FCM notification and if the user clicks on the notification it is possible to open an activity, but I wanted the user not to have to click on it.
FirebaseService.java
//--- Notificacao
public void createNotificationChannel(){
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//create a notification channel
NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
"Mascot Notification", NotificationManager
.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
public void sendNotification(String taskName){
NotificationCompat.Builder notifyBuilder = getNotificationBuilder(taskName);
//agora temos que entregar a notificacao
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
}
public NotificationCompat.Builder getNotificationBuilder(String taskName){
Intent intent = new Intent(this, TesteActivity.class);
PendingIntent p = getPendingIntent(NOTIFICATION_ID, intent, getApplicationContext());
return new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentText("titulo teste")
.setContentIntent(p)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
private PendingIntent getPendingIntent(int id, Intent intent, Context context){
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(intent.getComponent());
stackBuilder.addNextIntent(intent);
PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
return p;
}
TesteActivity.java
public class TesteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teste);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
}
instead of mNotifyManager.notify( call, which shows your Notification, just use startActivity(..? you may need also WakeLock and showOnLockScreen attribute set for this Activity in manifest
edit: and HERE you can find article with exactly your case tutorial
I have implemented push notifications using Azure's Notification Hub. I have noticed that they only have three override methods when extending NotificationHandler:
public void onReceive(Context context, Bundle bundle)
public void onUnregistered(Context context, String gcmRegistrationId)
public void onRegistered(Context context, String gcmRegistrationId)
Most push notification services have an onPushOpen() or onOpen() callback method which is called when a user presses on the push notification they received. How do I know when someone has clicked on the received push notification? I am experimenting with the demo. Everything works minus the concern I have said.
Link: https://github.com/Azure/azure-notificationhubs-samples/blob/master/Android/GetStartedFirebase/app/src/main/java/com/example/microsoft/getstartednh/MyHandler.java
public class MyHandler extends NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("message");
sendNotification(nhMessage);
if (MainActivity.isVisible) {
MainActivity.mainActivity.ToastNotify(nhMessage);
}
}
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSound(defaultSoundUri)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
For anyone else trying to figure this out, it is actually pretty simple. In the sendNotification() method, whatever information you want to keep track of when the push notification is opened add it as extras to your intent. For example.
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// seeking to do something specific when notification is opened if flag is set
intent.putExtra("onPushOpen", "performSomeAction");
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSound(defaultSoundUri)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
Now that you have done this. In onResume() check for that information. It will be empty (null) when push notification is not invoked, otherwise, it will have your information.
Bundle b = getIntent().getExtras();
// now retrieve what you want from the bundle.
This class won't to handle multiple GCM messages and show them on notification bar,currently handle only one, how can make it to handle multiple messages?
public class GCMIntentService extends GcmListenerService {
private static final String TAG = "GCMIntentService";
int notifyid = 0;
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "from:" + from);
Log.d(TAG, "message:" + message);
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notifyid, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("New Messsage")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent);
int numMessages = 0;
notificationBuilder.setContentText(message).setNumber(++numMessages);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifyid, notificationBuilder.build());
}
}
}
From the documentation:
public void notify (int id, Notification notification)
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
notifyid never appears to change in the code you've posted, which is why you only see a single notification.
Good day!
I have successfully sent push notification message to my app on android, and when I tap on the message, it launches my app. May I ask how do I pass intent/bundle to MainActivity from the push notification so that when the app is launched, it can display the push notification message in full within the app? Thank you very much!
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmMessageHandler.class.getName());
showNotification(context, intent);
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
private void showNotification(Context context, Intent intent) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
String title = intent.getExtras().getString("nTitle");
String message = intent.getExtras().getString("nMessage");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context);
Notification notification = mBuilder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.face)
.setColor(context.getResources().getColor(R.color.wallet_holo_blue_light))
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.fuckya))
.setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message).build();
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
Regards,
Lorkh
Replace to:
Intent mainActivityIntent = new Intent(context, MainActivity.class);
String title = intent.getExtras().getString("nTitle");
String message = intent.getExtras().getString("nMessage");
mainActivityIntent.putExtra("nTitle", title);
mainActivityIntent.putExtra("nMessage",message);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainActivityIntent), 0);
And retrieve this values inside your MainActivity via getIntent();
I'm developing an online radio application. The application works in the background. When I click the NotificationManager, radioclass starts working again. I want to call the radioclass that are running. How can I do?
player = MediaPlayer.create(this, Uri.parse("http://...../playlist.m3u8"));
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
}
});
player.start();
final int notificationID = 1234;
String msg = "mesajjj";
Log.d(TAG, "Preparing to update notification...: " + msg);
NotificationManager mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, RadioClass.class);
//Here RadioClass running again. But RadioClass already running. I should call RadioClass that is running.
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.logotam)
.setContentTitle("Test FM")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(pendingIntent);
mNotificationManager.notify(notificationID, mBuilder.build());
If you want to go back to the same activity you are currently running, you can do it like this:
Add the following tag on your AndroidManifest.xml:
<activity
........
android:launchMode="singleTop" >
........
</activity>
Modify your PendingIntent like this:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
With this modifications, you ensure that your activity will only have one instance at any given time. On your activity class, you can also override the onNewIntent method:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
This method will handle all of the additional calls to your activity.