I have followed this tutorial and when I try to send a message from Firebase console, onMessageReceived were called and createNotification were performed, no notification prompt shows up.
It suppose to prompt this but it didn't
Below is my MyAndroidFirebaseMsgService code
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.HashMap;
public class MyAndroidFirebaseMsgService extends FirebaseMessagingService
{
private static final String TAG = "MyAndroidFCMService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Log data to Log Cat
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//create notification
createNotification(remoteMessage.getNotification().getBody());
}
private void createNotification( String messageBody)
{
Intent intent = new Intent( this , ResultActivity.class );
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Test Notification")
.setContentText(messageBody)
.setAutoCancel( false )
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
}
Finally found that the notification were actually only appeared on the android drop down menu instead of popping up due to my device is running Android 4. I test again with Android 5 device and the notification pop up just like the tutorial.
Maybe you were missing notification notify.
Please try bellow code. it's working properly
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(RemoteMessage remoteMessage) {
Intent resultIntent = new Intent(this, MenuBarActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
HashMap<String, String> dataMap = new HashMap<String, String>(remoteMessage.getData());
resultIntent.putExtra(Constant.KEY_MESSAGE_BODY, dataMap);
resultIntent.putExtra(Constant.KEY_IS_NOTIFICATION, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getData().get(Constant.KEY_BODY)))
.setContentText(remoteMessage.getData().get(Constant.KEY_BODY))
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSound(defaultSoundUri);
// if (!BaseActivity.isInForeground()) {
notificationBuilder.setContentIntent(pendingIntent);
// }
// Generate ID
long time = new Date().getTime();
String tmpStr = String.valueOf(time);
String last4Str = tmpStr.substring(tmpStr.length() - 5);
int notificationId = Integer.valueOf(last4Str);
// Sets an ID for the notification
// int notificationId = Constant.NOTIFICATION_ID;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(notificationId, notificationBuilder.build());
}
Related
I'm currently making an app on android studio and I am getting stuck.
I've mananaged to have my notifications displayed when the app is open or closed, and when the app is in foreground, I receive the notification with the modifications I made on the MyFirebaseInstanceIdService file (see the file below), but i can't manage to display the notification when the app is closed or in background (meaning when it's a data notification) with the modifications I made (like the change of icon for the notification).
here is the code of the MyFirebaseInstanceIdService, the file managing my notifications
package com.shayru.myapplication.Service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.shayru.myapplication.R;
import java.util.Map;
import java.util.Random;
public class MyFirebaseInstanceIdService extends FirebaseMessagingService {
//Ctrl o
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getData().isEmpty())
showNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
else
showNotification(remoteMessage.getData());
}
private void showNotification(Map<String,String> data) {
String title = data.get("title").toString();
String body = data.get("body").toString();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID ="com.shayru.myapplication.test";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,"Notification",
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("CE Valeo");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
//R to take from "com.Shayru.myapp
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("Info");
notificationManager.notify(new Random().nextInt(),notificationBuilder.build());
}
private void showNotification(String title, String body) {
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID ="com.shayru.myapplication.test";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,"Notification",
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("CE Valeo");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
//R to take from "com.Shayru.myapp
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("Info");
notificationManager.notify(new Random().nextInt(),notificationBuilder.build());
}
}
I've been browsing the net for an answer but i can't find it myself despite reading the developer guides on the official android documentation site and code snippets from all over the Internet.
I've been practicing creating notifications on a new clean project, and despite creating a notification channel and the notification itself I still can't get it to run and get a message saying: "Failed to post notification on null channel". But im creating the channel, and assigning it to my notification just like it says everywhere. Im completely out of ideas and honestly i've been browsing stack for at least few hours now and every answer looks the same but it really didn't help me at all, so maybe if someone who's better than a begginer looks at my code can tell me what's wrong with my code? It's annoying because notifications are an important part of a project im working on, and it stopped me in my tracks.
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
findViewById(R.id.buckysButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createNotification(view);
}
});
}
public void createNotification(View view){
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
nm.createNotificationChannel(notificationChannel);
}
notification.setSmallIcon(R.drawable.ic_priority_high_black_24px);
notification.setTicker("Ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Title");
notification.setContentText("Body Body Body Body Body Body Body Body Body ");
notification.setChannel(NOTIFICATION_CHANNEL_ID);
notification.build();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
nm.notify(NOTIFICATION_ID, notification.build());
}}
By the way I'm developing for Android minimum level of 5.1 and I have been wondering if it's really necessary to put channels in my application, but I did it anyways since when im trying to do it without them I'm still getting exactly the same error.
EDIT: Im still struggling with this issue. Do I have to do something in the gradle files to be able to pass two arguments into the NotificationCompat.Builder constructor? It wont let me do it no matter what i do, i think thats the main problem here.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
Doesnt do it for me, it still doesnt want to take the channel_id as an argument.
new NotificationCompat.Builder(this);
is deprecated, try using
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
Here's a sample code, create a NotificationHelper class as follows,
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
public class NotificationHelper extends ContextWrapper {
private NotificationManager mNotificationManager;
private final String MY_CHANNEL = "my_channel";
private final long[] vibrationScheme = new long[]{200, 400};
/**
* Registers notification channels, which can be used later by individual notifications.
*
* #param context The application context
*/
public NotificationHelper(Context context) {
super(context);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// Create the channel object with the unique ID MY_CHANNEL
NotificationChannel myChannel =
new NotificationChannel(
MY_CHANNEL,
getResources().getString(R.string.notification_channel_title),
NotificationManager.IMPORTANCE_DEFAULT);
// Configure the channel's initial settings
myChannel.setLightColor(Color.GREEN);
myChannel.setVibrationPattern(vibrationScheme);
// Submit the notification channel object to the notification manager
getNotificationManager().createNotificationChannel(myChannel);
}
}
/**
* Build you notification with desired configurations
*
*/
public NotificationCompat.Builder getNotificationBuilder(String title, String body, Intent pendingIntent) {
Bitmap notificationLargeIconBitmap = BitmapFactory.decodeResource(
getApplicationContext().getResources(),
R.mipmap.ic_launcher);
return new NotificationCompat.Builder(getApplicationContext(), MY_CHANNEL)
.setSmallIcon(R.drawable.ic_notification_icon)
.setLargeIcon(notificationLargeIconBitmap)
.setContentTitle(title)
.setContentText(body)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setVibrate(vibrationScheme)
.setStyle(new NotificationCompat.BigTextStyle().bigText(body))
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
.setContentIntent(pendingIntent)
.setAutoCancel(true);
}
public NotificationManager getNotificationManager() {
if (mNotificationManager == null) {
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return mNotificationManager;
}
}
and then use it as follows,
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder builder = notificationHelper.getNotificationBuilder(title, message);
notificationHelper.getNotificationManager().notify(notificationID, builder.build());
Ok, maybe I'm bit late, but...
Try to shorten your channelId string.
Now it
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
Try
private static final String NOTIFICATION_CHANNEL_ID = "my_channel";
For me it was a very strange bug. When channelId was too long it don't show notification on my device.
Edit:
It was not too long or too short, just some string got banned in system. Also it not showed in Android notification settings screen.
I've found out what was missing. I was using android studio 2.3.3 instead of the newest 3.0.1 so I couldn't import some of the new functions through Gradle.
After that i only had to change my dependencies classpath to 'com.android.tools.build:gradle:3.0.1' and the problem was gone.
Thanks for help.
I am new to push notifications in android so i followed the following tutorial on android developer page.
http://developer.android.com/google/gcm/client.html
The thing i am not clear is in the intentservice class.It is shown below:
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.igloo.fragments.sportsfragment;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
//Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
//Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, sportsfragment.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
The thing that confuses me is the final method:
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Can someone please clarify why the pending intent is used here to DemoActivity.class.And also explain what this line does: mBuilder.setContentIntent(contentIntent);
My understanding is that it takes you to the class where you want to go when i click on the notifciation from the notification bar above.Is it right?
}
PendingIntent is set up as a "pointer" and stored by the system so that when the user selects the notification in the status bar the target activity specified in the notificationIntent can be called.
If you want to know something more http://examples.javacodegeeks.com/android/core/ui/notifications/android-notifications-example/
Updated MyService #CommonsWare
i have a service that if started will set up an alarm that triggers the notification.
This works fine and the alarms are canceled if the service is stopped.
i am trying to get the notification to open a new activity class but can not get it done
my service class is the following:
package com.example.andtip;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class BReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, DoSomething.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent("com.example.andtip"),0 );
PendingIntent pi2 = PendingIntent.getActivity(context, 0, myIntent,0 );
myNotification=new NotificationCompat.Builder(context)
.setContentTitle("This is a notification from the example alarm application.")
.setContentText("Notification")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
how should i link the intent pi2 to the notification?
i am trying to get the notification to open a new activity class but can not get it done
You are using getBroadcast() to create your PendingIntent. Use getActivity() to create a PendingIntent that starts up an activity. Make sure that the Intent you put in the PendingIntent is for an activity, and make sure that the activity has its entry in the manifest.
This is my code:
NotificationManager mNotificationManager = (NotificationManager) c.getSystemService(ns);
//Instantiate the notification
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification.Builder builder = new Notification.Builder(c)
.setTicker(tickerText)
.setWhen(when)
.setContentTitle("Test Notification")
.setContentText(arg1.getStringExtra("info"))
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true);
Notification notification = builder.getNotification();
mNotificationManager.notify(88, notification);
It works find, but using Notification notification = builder.getNotification(); is deprecated. as I should be doing Notification notification = builder.build();.
Problem is Eclipse isn't recognizing it as such, meaning it won't let me compile. The doc is clear that build() exists and its the preferred method, but its not working on my end. I would like to use non-deprecated code, so any help will be much appreciated.
imports
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
Be aware that import android.app.Notification.Builder; is saying its not being used.
If you want develop for version SDK lower than 11, you can use this code instead android.app.Notification.Builder class for creation notification:
private void createNotification(){
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "Hello", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, YourActivity.class);
Random r = new Random();
int notificationId = r.nextInt();
notificationIntent.putExtra("n_id", notificationId);
PendingIntent contentIntent = PendingIntent.getActivity(this, notificationId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "Party", "Welcome!", contentIntent);
mNotificationManager.notify(notificationId, notification);
}
You can cancel this notification in YourActivity like this:
public class YourActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
int notificationId = getIntent().getIntExtra("n_id", -1);
if (notificationId!=-1) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(notificationId);
}
}
}
This only happens when, You are compiling your app code against the version which does not hold required method/api (in your case it is build()).
If build is not available in the version you are compiling with, I will suggest you to compile with higher version of Android, You always have minimum sdk version in manifest for backward compatibility.
Thanks