I'm using Worklight Push Notification but on Android the push comes with no sound. I want to enable default sound (and LED if possible).
I'm using the sample push notification example code.
var notification = WL.Server.createDefaultNotification(notificationText, badgeDigit, {custom:"data"});
I also tried to assigning a value like notification.GCM.sound = "true" or notification.GCM.sound = "default" but it is playing continuous sound on some devices.
To accomplish this you will have to modify your app. Worklight will generate a skeleton class in your Android project, GCMIntentService.java
In order to add sound and flash the LED notification light, you will have to override the notify methods in the GCMIntentService class. Your file will look like this:
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
public class GCMIntentService extends
com.worklight.androidgap.push.GCMIntentService {
#Override
public void notify(Context context, String alert, int badge, String sound,
Intent intent) {
super.notify(context, alert, badge, sound, intent);
// call helper method
notifyLightAndSound(context);
}
#Override
public void notify(Context context, String tickerText) {
super.notify(context, tickerText);
// call helper method
notifyLightAndSound(context);
}
private void notifyLightAndSound(Context context) {
// Get the default notification sound
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// build a notification with the light and sound
// LED will be on for 1000 ms and off for 800 ms until you turn on your
// screen
Notification n = new Notification.Builder(context)
.setLights(Notification.DEFAULT_LIGHTS, 1000, 800)
.setSound(notification).build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// play sound and flash LED
mNotificationManager.notify(4, n);
}
}
This will flash the LED and play the default notification sound of your phone "different based on each phone".
I hope this helps to answer your question.
LED notification is not available.
See here: Led not working on Android using Unified Push Notification of worklight (6.0.0.2)
To use a custom notification sound (see supported media formats):
If the folder does not exist already, add a folder named raw under the existing native\res folder in yourProject\apps\yourApp\android\native
Place the sound file in the raw folder
To use default notification sound, try sending it empty:
notification.GCM.sound = "";
Related
Ever since adding support for Android O, Android devices running O receive an alert (tone or vibration) whenever my app's media controls notification gets updated (metadata or playback state changes). I'm looking for a way to disable this alert since it's not applicable to media style notifications.
Here is the code I use to create a media controls notification:
MediaDescriptionCompat description = metadata.getDescription();
String artistName = metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
String albumName = metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
Bitmap largeIcon = BitmapFactory.decodeResource(playbackService.getResources(),
R.drawable.vector_global_defaultsong);
NotificationCompat.Builder notificationBuilder = new NotificationCompat
.Builder(playbackService, NotificationHelper.CHANNEL_MEDIA_CONTROLS)
.setColor(ContextCompat.getColor(playbackService, R.color.colorAccent))
.setSmallIcon(R.drawable.logo_light_filled)
.setContentTitle(description.getTitle())
.setContentText(playbackService.getString(R.string.song_list_subtitle_format,
artistName, albumName))
.setContentIntent(createContentIntent())
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(playbackService,
PlaybackStateCompat.ACTION_STOP))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(playbackState.getState() == PlaybackStateCompat.STATE_PLAYING)
.setLargeIcon(largeIcon);
notificationBuilder.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
// show previous, play/pause, and next in compact view
.setShowActionsInCompactView(addActions(notificationBuilder))
.setMediaSession(sessionToken));
showNotification(notificationBuilder.build());
. . .
private void showNotification(final Notification notification) {
if (!started) {
mediaController.registerCallback(mediaControllerCallback);
playbackService.startForeground(NOTIFICATION_ID, notification);
started = true;
} else {
notificationManager.notify(NOTIFICATION_ID, notification);
}
if (playbackState.getState() == PlaybackStateCompat.STATE_PAUSED) {
playbackService.stopForeground(false);
}
}
Here is the code I use to create the notification channel:
public static final String CHANNEL_MEDIA_CONTROLS = "media_controls";
public static void createNotificationChannels(Context context) {
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel mediaControlsChannel = new NotificationChannel(CHANNEL_MEDIA_CONTROLS,
context.getString(R.string.notification_channel_media_controls),
NotificationManager.IMPORTANCE_HIGH);
mediaControlsChannel.setShowBadge(false);
getNotificationManager(context).createNotificationChannel(mediaControlsChannel);
}
}
Update: Setting the showBadge to false on the notification channel doesn't appear to do anything. I still receive a badge on the app icon when the media controls notification is shown. So it looks like the notification channel attributes that I set are not being applied.
Per the Migrating MediaStyle notifications to Android O, you should be using IMPORTANCE_LOW, which does not contain any sound - IMPORTANCE_HIGH channels have sound associated with them.
Android already reorders MediaStyle notifications higher in the tray, so using a higher importance is not necessary as it was on previous versions of Android.
NOTE: After changing the importance, you need to clear app data or reinstall the app in order to have this change take effect in notification channel.
I'm trying to push notifications to the end-users of the app when post is uploaded. It works fine when the app is in foreground but doesn't show up when then the app is in background or killed. Is there any way to show the notifications when the app is killed or running in the background.
Here is the node.js code which i'm using
const functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/promos').onWrite(event => {
var topic = "deals_notification";
let projectStateChanged = false;
let projectCreated = false;
let projectData = event.data.val();
if (((event.data.numChildren())-(event.data.previous.numChildren()))>0) {
let msg="notification arrived"
let payload = {
notification: {
title: 'Firebase Notification',
body: msg,
sound: 'default',
badge: '1'
}
};
admin.messaging().sendToTopic(topic, payload).then(function(response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
}).catch(function(error) {
console.log("Error sending message:", error);
});
}
});
and here is the MyFirebaseMessageService:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessageService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e("notification---",remoteMessage.getNotification().getBody());
sendnotification(remoteMessage.getNotification().getBody());
}
private void sendnotification(String body){
Intent intent = new Intent(this, MainActivity.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
PendingIntent pIntent = PendingIntent.getActivity(this, (int)
System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification.Builder n = new Notification.Builder(this)
.setContentTitle("Best Deals")
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, n.build());
}
}
Thanks.
I am sure the code is perfect. But there might be some problem with the device you are testing.Please try to test the code with some other device.
if the problem is that onMessageReceived() is called only when the app is in foreground, and when it's in background a notification is displayed but your method is not called... than that's working correctly. See the documentation:
Use notification messages when you want FCM to handle displaying a
notification on your client app's behalf. Use data messages when you
want to process the messages on your client app.
Read more here: https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
You are sending a notification-message. instead you should send a data-message
If the problem is different: when the app is in background nothing happen, it might be a problem of your device. See Push notifications using FCM not received when app is killed android
I wrote an IntentService for GCM Push Notifications.
I receive the Messages but something's wrong with displaying my Notification to the user.
Here's my Code:
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM test";
#Override
protected void onHandleIntent(Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!intent.getExtras().isEmpty()) { // has effect of unparcelling Bundle
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());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Post notification of received message.
sendNotification("message:\n" + intent.getStringExtra("message"));
Log.i(TAG, "Received: " + intent.getExtras().toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle("My notification")
.setContentText(msg);
Intent resultIntent = new Intent(this, PopupMessageActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(PopupMessageActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
I don't see the mistake. I mean, I copied the code from the Androids developer guide.
The only thing that this code does, is that the small icon (in this case "ic_notif") is showing in the notification-bar of the phone.
But there's no Text or Notification that pops up to the user.
I use android-studio.
My debug device is an huawai u8666e with android 4.0.3 (API 15).
At least i want this API level to be my minimum requirement for this app.
What you are seeing is normal designed Android behaviour for versions before Lollipop.
The design logic is that this method creates a cleaner interface and will not interrupt the user's current actions by placing a popup in front of their face. (there is a lot of debate over which method is better - iOS popups vs Android notifications).
Lollipop changes this slightly by creating a small popup at the top of the device window when a Notification is created.
If you really want to force a popup dialog to be shown, you should be looking at designing a "full screen" Notification.
See the Android Developer docs:
Notication.Builder.setFullScreenIntent(Intent)
Using this method, you can create a new Activity with any custom layout you want, and launch that instead of placing the Notification in the status bar.
(full implementation of a full screen notification would be beyond the scope of this post)
I would recommend against forcing full screen notifications except in rare cases, such as an Alarm Clock, or Phone Call app. I would, instead, recommend that you stick to the way Android was designed and work with the OS.
I am developing for Honeycomb and for days i am trying to solve this problem.
I have an notification service without intent (don`t need one), the problem is that after every call for displaymessage function the notification pup-up each time, so i get 100 notifications. I would like it to popup only once and after that only change the text of percent. Similar to downloading from market progress bar and percentage. I have isolated the function and created new testing code but with no success. If you look at this from other angle, i wish to change the text on existing notification without creating new notification.
Can you please help me?
Here is the whole code (after the isolation):
package com.disp;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.SystemClock;
public class DispalyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 100; i++) {
SystemClock.sleep(300);
displaymessage(""+i+"%");
}
}
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
Notification notification = new Notification(R.drawable.ic_launcher, "Notification Service", System.currentTimeMillis());
Context context = getApplicationContext();
notification.setLatestEventInfo(context, "Downloading Content:", string, null);
final int HELLO_ID = 2;
mNotificationManager.notify(HELLO_ID, notification);
}
}
Because each notification is uniquely identified by the NotificationManager with an integer ID, you can revise the notification by calling setLatestEventInfo() with new values, change some field values of the notification, and then call notify() again.
You can revise each property with the object member fields (except for the Context and the notification title and text). You should always revise the text message when you update the notification by calling setLatestEventInfo() with new values for contentTitle and contentText. Then call notify() to update the notification. (Of course, if you've created a custom notification layout, then updating these title and text values has no effect.)
from
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Could anyone possibly offer some advice on how to setup Status bar notifications in Android?
My skillset is all based around design/front-end dev (hence using phonegap) so I'm a beginner with Eclipse.
I have read this tutorial - http://androidforbeginners.blogspot.com/2010/02/how-to-create-status-bar-notifications.html and have pasted the code into the activity area of my Android Manifest file. But I don't quite understand how it will work. If I compile this now as an APK and install it on a phone -- is it now ready to receive notifications? If so how do I send them, and where do I type the sending code?
Hopefully it's fairly simple as my boss is hoping that I'll have it completed before christmas!
Cheers for your help.
All the best
Paul
You want status bar notification? If yes...you are lucky...here's a plugin which I already created for phonegap. Look around for how to embed the external plugin in android.
https://github.com/phonegap/phonegap-plugins/tree/master/Android/StatusBarNotification
Here you can find better explanation with source codes about notifications.
Notification can be a reaction on some event. For instance, you can develop a simple application with one button. When you press this button a notification will be displayed in the status bar.
About the development. You should install Android SDK, create an emulator of the device. Also it is very useful to install Android ADT - this is a pluging for Eclipse to help to develop Android applications. After that when you build an application it will be automatically installed on the emulator.
Here is the code how to make a simple notification:
package your.package
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AcNotificationTestMain extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private static final int SEND_ID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mBtnSend = (Button) findViewById(R.id.button1);
mBtnSend.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Log.v("","OnClick...");
// Create an object of Notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.sym_action_email; // icon from resources
CharSequence tickerText = "New Notification"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = "My notification"; // expanded message title
CharSequence contentText = "Click me!"; // expanded message text
Intent notificationIntent = new Intent(this, AcNotificationTestMain.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(SEND_ID, notification);
}
}
And layout file:
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="#string/hello"/>
<Button android:id="#+id/button1" android:text="#string/AcNotificationTest_BtnSendNotificationText" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>