How to check which notification id is clicked? - java

My application is receiving GCM notifications. I have different type of notifications and at some point the user can have more than one notification in the status bar. However I need to know which one exactly he clicked on. In the GCM onMessage Im setting them with
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(notification_id), notification);
I need to get that notification_id after the click on the notification. I am pretty sure that's something simple but I couldnt find any info about it.
Here are the onMessage from GCMIntentService
#Override
protected void onMessage(Context context, Intent data) {
String content_title;
String content_text;
String event_id;
String content_info;
String url;
String match_id;
// Message from PHP server
content_title = data.getStringExtra("content_title");
content_text = data.getStringExtra("content_text");
content_info = data.getStringExtra("content_info") + "'";
event_id = data.getStringExtra("event_id");
match_id = data.getStringExtra("match_id");
url = data.getStringExtra("url");
NOTIFICATION_URL = url;
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, GCMMessageView.class);
// Pass data to the new activity
intent.putExtra("message", content_title);
intent.putExtra("url", url);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Options opts = new Options();
opts.inDither = true;
opts.inScaled = false;
/* Flag for no scalling */
// Create the notification with a notification builder
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(drawable_small).setLargeIcon(drawable_big)
.setWhen(System.currentTimeMillis()).setTicker(content_title)
.setContentTitle(content_title).setContentInfo(content_info)
.setContentText(content_text).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(match_id), notification);
try {
Uri notification2 = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification2);
r.play();
} catch (Exception e) {
}
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
And there`s the on click
String msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.hasExtra("url"))
msg = intent.getExtras().getString("url");
Log.e("URL", msg);
setContentView(R.layout.activity_main);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(msg
+ "?device_id="
+ GCMIntentService.DEVICE_REGISTRATION_ID.toString()));
startActivity(browserIntent);
// Toast.makeText(getApplicationContext(),
// GCMIntentService.DEVICE_REGISTRATION_ID, Toast.LENGTH_LONG).show();
}

You can go through the below code, You have to ser Notification object as per your need.
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
Intent intent = new Intent(context, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("message", YOUR_DATA);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID,
intent, 0);
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, when);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify((int) when, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(when)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify((int) when, notification);
}
When user click on any notification, it will re-direct to NotificationActivity class.
In this activity, in OnCreate() method you can get your data that is set.
Intent intent = getIntent();
if (intent.hasExtra("message"))
String msg = intent.getExtras().getString("message");
I think it will help.

Related

How to open an activity on the lock screen after FCM notification

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

Get multiple GCM messages

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.

Alternative way on how to change setLatestEventInfo in notification receiver

Hi i got stock in this point wherein "setLatesEventInfo" has an error. i know that setLatestEventInfo doesnt run on API 23 and up. can someone help me on how to make this code run ? i mean alternative way , same function but different coded. this is a receiver function. i am doing a notification on my Mainactivity. The only error here is the receiver ,i tried the builder notification , but since this is a receiver ,builder cant apply
Receiver.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by my pc on 12/1/2015.
*/
public class Receiver extends BroadcastReceiver {
private static final Object ACTION = "MyNotification";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action)) {
//do what you want here
Variables.numMessages++;
generateNotification(context,"MyNotification");
}
}
private void generateNotification(Context context, String message) {
long when = System.currentTimeMillis();
int icon = R.drawable.ic_od_icon_24dp;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
// String subTitle = context.getString(R.string.app_name);
String subTitle = "some text";
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("content", message);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.setLatestEventInfo(context, title, subTitle, intent);
//To play the default sound with your notification:
//notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
MainActivity.java
public class MainActivity extends Activity {
int NOTIFICATION_ID = 1;
int LED_ON_MS = 200;
int LED_OFF_MS = 600;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onGenNoti(View v) {
// Check readCount
Variables.readCount = Variables.numMessages;
PendingIntent pIntent =
PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MainActivity.class), 0);
if (Variables.numMessages > 0) {
Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("You Have " + Variables.numMessages + " message")
.setContentTitle("test")
.setContentText("")
.setSmallIcon(R.drawable.ic_od_icon_24dp)
.setContentIntent(pIntent).getNotification();
noti.defaults |= Notification.DEFAULT_SOUND;
noti.defaults |= Notification.DEFAULT_VIBRATE;
noti.ledARGB = Color.BLUE;
noti.ledOnMS = LED_ON_MS;
noti.ledOffMS = LED_OFF_MS;
noti.flags = Notification.FLAG_SHOW_LIGHTS;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, noti);
}
}
}
Now you have to generate your notification like this
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context);
// set intent so it does not start a new activity
Notification notification = builder
.setContentIntent(yourPendingIntent)
.setSmallIcon(icon)
.setWhen( System.currentTimeMillis();)
.setContentTitle(title)
.setContentText(message).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notifId, notification);

Android Notification into Alert Notification

I built an notification which works so far.
Since I did not know that it works only inside of my application I read through some articles and saw that I need an 'Alarm Notification'.
I tried varous things but none did not work, now I am asking here.
My Notification in my Mainactivity looks like this:
public static final int NOTIFICATION_ID_01 = 1;
public void sendNotificationIfTimeEnd01() {
Context context = getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
PendingIntent pendingIntent01 = PendingIntent.getActivity(this, 1, intent01, 0);
NotificationCompat.Builder builder01 = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pendingIntent01)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setContentTitle(gamesJuliToStringArray[0])
.setContentText("Ready")
.setSubText("click");
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID_01, builder01.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
I am accesing this notification in my Fragment if a specific conditions happens:
final MainActivity activity = (MainActivity) getActivity();
if (i = 10) {
activity.sendNotificationIfTimeEnd01();
editor.putBoolean("notification01", true);
editor.apply();
}
Again I want to transform this Notification into an 'Alarm' / 'Alarm Notification'.
I appreciate any response!

Cancel notification not working

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

Categories