When I push notification from fore base I faced this error
E/AudioFlinger: not enough memory for AudioTrack size=131296
02-26 21:00:38.035 1328-1328/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
02-26 21:00:38.035 2145-2256/? E/AudioRecord: AudioFlinger could not create record track, status: -12
02-26 21:00:38.039 2145-2256/? E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
02-26 21:00:38.039 2145-2256/? E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
02-26 21:00:38.040 2145-2256/? E/ActivityThread: Failed to find provider info for
com.google.android.apps.gsa.testing.ui.audio.recorded
This is the on receive method
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Related
I have a xamarin.forms android application on playstore. In which I have implemented foreground service to fire AlarmManager notifications (for android version >= Q). I can see some crashes logged on platstore for my app which I think is related to these foreground service and AlarmManager notifications. Here I am posting crash logs from the playstore that is all I have.
java.lang.IllegalStateException
crc640e87e93c5dbd1629.AlarmReceiver.n_onReceive
java.lang.RuntimeException:
at android.app.ActivityThread.handleReceiver (ActivityThread.java:4125)
at android.app.ActivityThread.access$1400 (ActivityThread.java:270)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2062)
at android.os.Handler.dispatchMessage (Handler.java:107)
at android.os.Looper.loop (Looper.java:237)
at android.app.ActivityThread.main (ActivityThread.java:7948)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1075)
Caused by: java.lang.IllegalStateException:
at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1687)
at android.app.ContextImpl.startService (ContextImpl.java:1632)
at android.content.ContextWrapper.startService (ContextWrapper.java:683)
at android.content.ContextWrapper.startService (ContextWrapper.java:683)
at crc640e87e93c5dbd1629.AlarmReceiver.n_onReceive (Native Method)
at crc640e87e93c5dbd1629.AlarmReceiver.onReceive (AlarmReceiver.java:29)
at android.app.ActivityThread.handleReceiver (ActivityThread.java:4116)
here is another log
java.lang.ClassNotFoundException
crc643622be0927bcf195.NotificationService.n_onStartCommand
java.lang.RuntimeException:
at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3755)
at android.app.ActivityThread.-wrap23 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1744)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6780)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1500)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1390)
Caused by: java.lang.ClassNotFoundException:
at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass (ClassLoader.java:380)
at java.lang.ClassLoader.loadClass (ClassLoader.java:312)
at crc643622be0927bcf195.NotificationService.n_onStartCommand (Native Method)
at crc643622be0927bcf195.NotificationService.onStartCommand (NotificationService.java:31)
at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3738)
Here is the NotificationService class :
[Service]
public class NotificationService : Service
{
private bool isStarted;
private int HIDDEN_NOTIFICATION_SERVICE_ID = 1;
private string HIDDEN_NOTIFICATION_CHANNEL_ID = "1";
private string HIDDEN_NOTIFICATION_NAME = "Hidden Notification Service";
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (!isStarted)
{
CreateHiddenNotificationChannel();
DispatchNotificationThatServiceIsRunning();
isStarted = true;
}
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
// Remove the notification from the status bar.
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Cancel(HIDDEN_NOTIFICATION_SERVICE_ID);
isStarted = false;
base.OnDestroy();
}
void CreateHiddenNotificationChannel()
{
NotificationChannel hiddentNotificationChannel = new NotificationChannel(HIDDEN_NOTIFICATION_CHANNEL_ID, HIDDEN_NOTIFICATION_NAME, NotificationImportance.Low);
hiddentNotificationChannel.LockscreenVisibility = NotificationVisibility.Secret;
hiddentNotificationChannel.SetSound(null, null);
hiddentNotificationChannel.EnableVibration(false);
NotificationManager notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);
notificationManager.CreateNotificationChannel(hiddentNotificationChannel);
}
//start a foreground notification to keep app alive
private void DispatchNotificationThatServiceIsRunning()
{
Intent intent = new Intent(this, typeof(BroadcastReceiver.CustomReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(
this,
1,
intent,
PendingIntentFlags.UpdateCurrent
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, HIDDEN_NOTIFICATION_CHANNEL_ID)
.SetDefaults((int)NotificationDefaults.All)
.SetSmallIcon(Resource.Drawable.icon)
.SetSound(null)
.SetContentIntent(pendingIntent)
.SetPriority(NotificationCompat.PriorityMin)
.SetAutoCancel(false)
.SetContentTitle(AppResources.MyApp)
.SetContentText(AppResources.ForegroundServiceNotificationMsg)
.SetStyle(new NotificationCompat.BigTextStyle().BigText(AppResources.ForegroundServiceNotificationMsg))
.SetOngoing(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
StartForeground(HIDDEN_NOTIFICATION_SERVICE_ID, builder.Build());
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
Starting above service from MainActivity and from BroadcastReceiver class when user reboots the device
if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Q)
Android.App.Application.Context.StartForegroundService(new Intent(Android.App.Application.Context, typeof(Services.NotificationService)));
I need to open a ContentPage while receiving FCM notification like call screen. It's a chat video application. I'm using Xamarin.Forms and TokBox. Help me solving this.
On Foreground notifications, you could do that with FirebaseMessagingService before sending the notification on device.
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "From: " + message.From);
var body = message.GetNotification().Body;
Log.Debug(TAG, "Notification Message Body: " + body);
//do something here
SendNotification(body, message.Data);
}
void SendNotification(string messageBody, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.notification)
.SetContentTitle("FCM Message")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
}
For more details, you could refer to the MS document. https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows
I am able to receive the message but only display in the log. I wanted to display as a notification at the top of the screen.
Here is my code:
MainActivity.cs
static readonly string TAG = "MainActivity";
internal static readonly string CHANNEL_ID = "my_notification_channel";
internal static readonly int NOTIFICATION_ID = 100;
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
UserDialogs.Init(this);
CreateNotificationChannel();
CrossMedia.Current.Initialize();
Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this;
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App(FirebaseInstanceId.Instance.Token));
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channel = new NotificationChannel(CHANNEL_ID,
"FCM Notifications",
NotificationImportance.Default)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
In MyFirebaseMessagingService class
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "From: " + message.From);
var body = message.GetNotification().Body;
Log.Debug(TAG, "Notification Message Body: " + body);
SendNotification(body, message.Data);
}
void SendNotification(string messageBody, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this,
MainActivity.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
//.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentTitle("FCM Message")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
}
}
I can received the message in here: Log.Debug(TAG, "Notification Message Body: " + body); and it will log the body of the message however after calling the SendNotification function, then in this line:
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
It will have error: Java.Lang.IllegalArgumentException: <Timeout exceeded getting exception details>
Where can I am getting the value for CHANNEL_ID and NOTIFICATION_ID? Currently, it has value: my_notification_channel and 100 respectively as same as in the docs. Is this the reason why I'm having this error?
Please help. Thank you.
You had a problem with the Notification construction
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification) //you could not commen it
.SetContentTitle("FCM Message")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
SetSmallIcon is a required parameter, otherwise you will build an error
I am using this code to show notification in my android Application. This is working fine in all android version but no notification is showing in Android 9.
I tried to implement this with different method but nothing worked.
public void showNotification(String heading, String description, String imageUrl, Intent intent){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
createChannel();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.logo)
.setContentTitle(heading)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Description");
notificationManager.createNotificationChannel(channel);
}
Thanks..
Hi this is very Late Answer but I still want to mark the mistake in the code as well as the working code snippet so that It can help others.
you are having two instance of notificationManager on in the showNotification(..) function and another in the createChannel() function. You must create channel in the same instance of the notificationManager so your working code will be like:
public void showNotification(String heading, String description, String imageUrl, Intent intent){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(heading)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
createChannel(notificationManager);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(NotificationManager notificationManager){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Description");
notificationManager.createNotificationChannel(channel);
}
Call Like:
showNotification("Heading","Description","",new Intent(this,MainActivity.class));
The Results:
Here is code to generate inline notification everything is working fine but I don't want to show MessageReply.class.
Current problem: A white screen is appear as pending intent is called
while sending message.
Required result: No such white screen work same like whatsapp inline
notification.
void buildNotification(String messageValue) {
Intent intent = new Intent(this, Test.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Consts.EXTRA_MESSAGE, messageValue);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(Consts.GCM_NOTIFICATION)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setSound(defaultSoundUri)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageValue))
.setContentText(messageValue)
.addAction(buildReplyFromNotification(extras));
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private NotificationCompat.Action buildReplyFromNotification(Bundle data) {
String replyLabel = getResources().getString(R.string.reply_label);
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build();
// Create the reply action and add the remote input.
return new NotificationCompat
.Action
.Builder(R.drawable.ic_send, getString(R.string.reply_label), buildReplyPendingIntent(data))
.addRemoteInput(remoteInput)
.build();
}
private PendingIntent buildReplyPendingIntent(Bundle messageValue) {
Intent intent = new Intent(this, MessageReply.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(Consts.EXTRA_DIALOG_ID, messageValue.getString("dialog_id"));
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
try to use theme for that activity android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen"