Hi im working on a project that uses push notifications to push out information in a text format. Only when i receive the push notification the text is cut off and replaced with "..."
Im using the NotificationCompaq builder to build my notifications when the app receives the information from the receiver.
Here is my GCMBroadcastReceiver Im pretty sure the issue is in the Builder but Im not sure what i need to do to fix it.
import utilities.CommonUtilities;
import android.app.Activity;
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;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
/**
* Handles the incoming messages from the server.
*
*/
public class GCMBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
String message = intent.getExtras().getString("price");
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
intent.getExtras().toString());
} else {
sendNotification(message);
}
setResultCode(Activity.RESULT_OK);
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.icon)
.setContentTitle(CommonUtilities.pushTitle)
.setStyle(new NotificationCompat.BigTextStyle())
.setContentText(msg)
.setLights(0xff00ff00, 300, 1000)
.setVibrate(CommonUtilities.pattern);
Log.d(TAG, "Notification built " + mBuilder.toString());
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Toast.makeText(ctx, "New Message: " + msg, Toast.LENGTH_LONG).show();
}
}
Any help on this would be greatly appreciated thanks.
Edit
Ive checked the Message received from the GCM before my app builds the notification and i am receiving the full message there is nothing being cut off during the receiving of the message so it is definitely something to do with the Notification builder. I Just cannot seem to figure out whats causing it to do that.
Related
When I install the app directly from android studio onto my phone per usb everything works well. I am working with push notifications that work with this method. But when I export my app in android studio and get the apk file and then install it per this apk file onto my phone everything works but not the notification??
Do you understand what I mean?
I can play my app per android studio directly onto my phone and it works 100% well ( I also get the expected push notifications).
After the export I get an apk file. I install this apk file manually and I get my app which looks great at first, only the notifications dont come although they come when I install it per android studio directly.
What am I doing wrong? Isnt the apk file the right file? Maybe I need another file? The code must be good because everything is fine when pushing play in android studio.
EDIT: Here is my code for the notifications:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.util.Random;
public class NotificationHelper extends ContextWrapper {
private static final String TAG = "NotificationHelper";
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannels();
}
}
private String CHANNEL_NAME = "High priority channel";
private String CHANNEL_ID = "com.example.notifications" + CHANNEL_NAME;
#RequiresApi(api = Build.VERSION_CODES.O)
private void createChannels() {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("this is the description of the channel.");
notificationChannel.setLightColor(Color.RED);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
public void sendHighPriorityNotification(String title, String body, Class activityName) {
Intent intent = new Intent(this, activityName);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 267, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
// .setContentTitle(title)
// .setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setStyle(new NotificationCompat.BigTextStyle().setSummaryText("summary").setBigContentTitle(title).bigText(body))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
NotificationManagerCompat.from(this).notify(new Random().nextInt(), notification);
}
}
And here is my code where I call the notification:
package com.example.geofencing1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.google.android.gms.maps.model.LatLng;
import java.util.List;
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "GeofenceBroadcastReceiv";
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// Toast.makeText(context, "Geofence triggered...", Toast.LENGTH_SHORT).show();
NotificationHelper notificationHelper = new NotificationHelper(context);
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()){
Log.d(TAG, "onReceive: Error receiving geofence event...");
return;
}
List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence: geofenceList) {
Log.d(TAG, "onReceive: " + geofence.getRequestId());
}
// Location location = geofencingEvent.getTriggeringLocation();
int transitionType = geofencingEvent.getGeofenceTransition();
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
Toast.makeText(context, "GEOFENCE_TRANSITION_ENTER", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_ENTER", "", MapsActivity.class);
break;
case Geofence.GEOFENCE_TRANSITION_DWELL:
Toast.makeText(context, "GEOFENCE_TRANSITION_DWELL", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_DWELL", "", MapsActivity.class);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
Toast.makeText(context, "GEOFENCE_TRANSITION_EXIT", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_EXIT", "", MapsActivity.class);
break;
}
}
}
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());
}
Successfully implemented Firebase in my app for sending push notifications about my blog, but now I want to know how a user can "turn off" the notifications that I send to the app, here is my code:
package com.lfcchile;
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;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by Jona on 7/23/16.
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_menu_destacado)
.setContentTitle("LFC Chile")
.setContentText(remoteMessage.getNotification().getBody())
.setTicker("Ticker")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Ideas please? thanks in advance!!
you can add some kind of Shared Prefences, and store the value gotten from the user. And then get the value first after getting the notification, if the value of the user is in such case true, then skip the creation of the notification.
You can have a Toggle button for their preferences and then check the value of the toggle before you execute your code. Thus, it becomes as simple as a if-else statement.
package com.lfcchile;
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;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by Jona on 7/23/16.
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_menu_destacado)
.setContentTitle("LFC Chile")
.setContentText(remoteMessage.getNotification().getBody())
.setTicker("Ticker")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(this.isEnabled == true){ // if statement added here
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
}
This one will work! Make sure the isEnebled variable is Global.
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/
Edit: It's fixed even though my code isn't perfect. I forgot to register this BroadCastReceiver in my Android Manifest file. Face Palm.
I'm having trouble getting my notification to work. It would help if I get some meaningful error message but I have no idea how to debug this.
Here's the code of the broadcast receiver:
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.util.Log;
public class ThisDoesNotWork extends BroadcastReceiver{
private Intent myIntent;
private PendingIntent myPending;
private static final int MY_NOTIFICATION_ID = 1;
private final CharSequence text1 = "Text1";
private final CharSequence text2 = "Text2!";
#Override
public void onReceive(Context context, Intent intent) {
myIntent = new Intent(context, MainActivity.class);
myPending = PendingIntent.getActivity(context, 0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
Notification.Builder myNote = new Notification.Builder(context).setTicker(
"Take a Selfie!")
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true).setContentTitle(text1)
.setContentText(text2)
.setContentIntent(myPending);
NotificationManager mNotify = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Log.i("Receiver", "Notification created.");
mNotify.notify(MY_NOTIFICATION_ID,myNote.getNotification());
Log.i("Receiver", "Notification sent.");
}
}
My program compiles but this notification gets ignored.
The error message I get is: Ignoring notification with icon==0; Notification(contentView =null vibrate=null...
Can anyone bring me 1 step closer to a solution?
Per the required notification contents, you must include:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
It appears you are missing the content title, causing your notification to get ignored.