Alternative way on how to change setLatestEventInfo in notification receiver - java

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

Related

Extra null for Android Notification with PendingIntent

I am trying to send a int Extra to an Activity when a notification is tapped. When I tap the notification the activity launches, but the extra is always null.
I have checked a lot of similar questions but they haven't helped me solve the problem. (I tried using onNewIntent() but it was never called). How can I successfully send the Extra?
This is the BroadcastReceiver where the intent is created:
public class EventAlarmNearReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent nextIntent = new Intent().setClass(context, EventActivity.class);
nextIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int id = 1234;
nextIntent.putExtra("Id", (long) id);
nextIntent.setAction("nearReceiverAction");
PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 1022, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String text = "Your " + intent.getStringExtra("Name") + " is starting soon. Please read your documents.";
NotificationsDeliver.getInstance().sendNotification(context, "Meeting Mate", text, nextPendingIntent);
}
}
This is the method from NotificationsDeliver where the notification is sent:
public void sendNotification(#NonNull Context context, String title, String text, PendingIntent pendingIntent ) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_event_note_white_24dp)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[] { 1000, 1000, 1000 })
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(999, builder.build());
}
This is onCreate method from EventActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
long id = intent.getLongExtra("id", 0);
}
I would guess that it's because you have capitalized the word "id" differently when putting vs getting the extra; compare:
nextIntent.putExtra("Id", (long) id);
// ^^^^
vs
long id = intent.getLongExtra("id", 0);
// ^^^^
Try using the same capitalization for both.

Why do I have to double click by a notification to close it when my app was closed?

I'm creating a ClockApp for Android. I have AlarmBroadcastReceiver which gives me a notification with the button close alarm and when an user clicks by that button the notification will be disappeared. However, it doesn't work when my app was closed. For example, I set alarm at 7:00 am and I closed my app then I waked up and I found on my phone a notification close alarm I clicked by that button but I just was redirected to a main activity then I clicked again and only then the notification will be disappeared. Why do I have to click two times? However, if my app isn't closed I have to click only one time and the notification will be disappeared. I hope you'll help me with my problem)
Code: (I have MainActivity with tabs)
MainActivity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// cancel notifications
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (intent.getBooleanExtra("alarm_cancel_notification", false)) {
if (notificationManager != null) {
notificationManager.cancel(1);
}
}
}
AlarmFragment:
private void startAlarm() {
Intent intent = new Intent(getContext(), AlarmManagerBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getContext(),
1,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= 23) {
AlarmManager.AlarmClockInfo alarmClockInfo =
new AlarmManager.AlarmClockInfo(mCalendar.getTimeInMillis(), pendingIntent);
mAlarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
}
}
BroadcastReceiver:
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static final int ALARM_EXPIRED_NOTIFICATION_ID = 1;
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("alarm_cancel_notification", true);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(
context.getPackageName(),
R.layout.partial_notification);
remoteViews.setTextViewText(
R.id.cancel_button_notification,
context.getString(R.string.alarm_notification));
remoteViews.setOnClickPendingIntent(
R.id.cancel_button_notification,
notificationPendingIntent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context,
ChannelIdApp.CHANNEL_ID);
builder.setAutoCancel(true)
.setTicker("Alarm")
.setCustomContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setSmallIcon(R.drawable.ic_stat_notify_clock);
Notification notification = builder.build();
notification.flags = notification.flags | Notification.FLAG_INSISTENT;
if (notificationManager != null) {
notificationManager.notify(ALARM_EXPIRED_NOTIFICATION_ID, notification);
}
}
}
Channel Id:
public class ChannelIdApp extends Application {
public static final String CHANNEL_ID = "clock_channel_id";
#Override
public void onCreate() {
super.onCreate();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID,
"Clock notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableVibration(true);
notificationChannel.enableLights(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
}
Manifest:
<activity
android:launchMode="singleTop"
android:name=".activities.MainActivity"
android:screenOrientation="portrait" />
<receiver
android:exported="false"
android:name=".AlarmManagerBroadcastReceiver" />
try adding .setAutoCancel(true); in your AlarmManagerBroadcastReceiver class after this line
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context,
ChannelIdApp.CHANNEL_ID);
builder.setAutoCancel(true)
.setTicker("Alarm")
.setCustomContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setSmallIcon(R.drawable.ic_stat_notify_clock)
// <<here>> ;

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.

How to check which notification id is clicked?

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.

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