Group fcm message from every chat room separately - firebase-cloud-messaging

I have already succeeded to send/receive from/to group fcm
the problem is:
I need to collect the message coming from the same group together Like Facebook Messenger :
Application Name,then chat room name,then messages from the same room
*
Example : I need instead of the current
separated messages in attached photo:
Learning ways <<the name of app
num2 <<room name
Mon: 6 <<message1
Mon: 7 <<message2
Mon: 8 <<message3
Current Notifications Call:
#RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
private void showOreoNotification() {
OreoNotification oreoNotification = new OreoNotification(this);
Notification.Builder builder = oreoNotification.getOreoNotification(title, sender_name + body, pendingIntent,
defaultSound, icon).setLargeIcon(senderImages);
oreoNotification.getManager().notify(i, builder.build());
i++;
}
private void showOLdNotifications() {
assert icon != null;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(Integer.parseInt(icon))
.setContentTitle(title)
.setContentText(sender_name + body)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent).setLargeIcon(senderImages);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(i, notificationBuilder.build());
i++;
}

You can use InboxStyle for Android 4.1+
Message format:
val str1:String = "%s : %s".format(sender, message)
InboxStyle:
Notification notif = new Notification.Builder(mContext)
.setContentTitle(room_name)
.setContentText(subject)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(aBitmap)
.setStyle(new Notification.InboxStyle()
.addLine(str1)
.addLine(str2)
.setContentTitle("")
.setSummaryText("+1 more"))
.build();
You can use MessagingStyle for Android 7+
var notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setStyle(NotificationCompat.MessagingStyle("me")
.setConversationTitle(room_name)
.addMessage(message1, timestamp1, null) // Pass in null for you.
.addMessage(message2, timestamp2, user2)
.addMessage(message3, timestamp3, user3)
.build()

Related

Push notification after successful payment for mobile apps

I need help how to send push notifications on successful payment with transaction I'd to user
Use one of the background workers if you want to check the status of your transaction in background. I will use WorkManager.
implementation "android.arch.work:work-runtime:1.0.1"
public class SynchronizeWorker extends Worker {
static final String TAG = "MYWORKER";
public SynchronizeWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
private Notification getNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"WTF_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("WTF_CHANNEL_DESCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
// specify the class of the activity you want to open after click on notification
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
intent,
0);
return new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getApplicationContext().getResources().getString(R.string.notification_header))
.setContentText(getApplicationContext().getResources().getString(R.string.notification_text))
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.build();
}
#NonNull
#Override
public Result doWork() {
Log.d(TAG, "status checking started");
// check your transaction status here and show notification
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Log.d(TAG, "status checking finished");
}
Log.d(TAG, "status checking finished");
NotificationManagerCompat
.from(getApplicationContext())
.notify((int)(Math.random() * 10), getNotification());
return Result.success();
}
}
And then enqueue worker where you want to check status
OneTimeWorkRequest myWorkRequest = new OneTimeWorkRequest.Builder(SynchronizeWorker.class).build();
WorkManager.getInstance().enqueue(myWorkRequest);
I understand that it is probably not exactly what you want, but hope it will help somehow:)

Notification "setSound()" in Android 8

Here's the question, the code of notification can't work with Android 8.
I can't set the notification sound myself. The only result it shows is the system sound "Bee".
Here's my code:
if(Build.VERSION.SDK_INT>=26) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "channel_1";
String description = "123";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, "123", importance);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setLightColor(Color.GREEN);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
AudioAttributes aa = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
mChannel.setSound(Uri.parse("android.resource://com.example.lenovo.projectmonitor/" + R.raw.video11),aa);
manager.createNotificationChannel(mChannel);
Notification notification = new NotificationCompat.Builder(NotificationService.this, "channel_1")
.setContentTitle("new alarm")
.setContentText(nameAll.get(0))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
manager.notify(1, notification);
}
use setSound method in both NotificationChannel and NotificationCompat.Builder class. example
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
channel.setSound(null, null);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
and creating buileder:
public void buildNotification(Class className, int smallIconId) {
createNotificationChannel();
// Create an Intent for the activity you want to start
Intent intent = new Intent(context, className);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
// TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// stackBuilder.addNextIntentWithParentStack(intent);
//// Get the PendingIntent containing the entire back stack
// PendingIntent pendingIntent =
// stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder
.setSmallIcon(smallIconId)
.setContentTitle("Recording Audio..")
// .setContentText("Much longer text that cannot fit one line...")
// .setStyle(new NotificationCompat.BigTextStyle()
// .bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(null)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
// notificationId is a unique int for each notification that you must define
// notificationManager.notify(notificationId, mBuilder.build());
// mBuilder.setContentTitle("changed it");
// notificationManager.notify(notificationId, mBuilder.build());
// mHandler.postDelayed(new Runnable() {
// #Override
// public void run() {
// }
// }, 3000);
}

youtube live broadcast lifeCycleStatus stuck on 'liveStarting'

I'm trying to figure out what i'm doing wrong when broadcast to live. I have my apk on my android phone stream to youtube. I have no problem streaming for the first time. But if I stop it for about 2 - 3 minutes, and stream again, the lifeCycleStatus of the boardcast keep stay at "liveStarting" and my video is not visible to audience. If I stop long enough, restart stream, the status will go 'live' in about 10 seconds. I have enableMonitorStream disable, and also try LiveBroadcasts.Transition, but it return error redundantTransition. But the lifeCycleStatus wouldn't turn to 'live'. I also try create a new live broadcast and live stream and change the status to 'live' manually, but both get stuck on 'liveStarting'.
public class YoutubeService {
private WeakReference<Context> context;
private static final String PREF_ACCOUNT_NAME = "youtube_account_name";
private static final String[] SCOPES = {YouTubeScopes.YOUTUBE};
private GoogleAccountCredential mCredential;
private YouTube mService;
public YoutubeService(Context context) {
this.context = new WeakReference<Context>(context);
// create account credential
mCredential = GoogleAccountCredential.usingOAuth2(
context, Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
mCredential.setSelectedAccountName("xxxx#gmail.com");
// create youtube builder
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new YouTube.Builder(
transport, jsonFactory, mCredential)
.setApplicationName("My App Name")
.build();
}
// AsyncTask<Void, Void, Map<String, String>>
private void getRtmpUrl() {
try {
// get livebroadcast list
YouTube.LiveBroadcasts.List liveBroadcastRequest = mService.liveBroadcasts().list("id,snippet,contentDetails,status");
liveBroadcastRequest.setBroadcastType("persistent");
liveBroadcastRequest.setMine(true);
LiveBroadcastListResponse liveBroadcastListResponse = liveBroadcastRequest.execute();
List<LiveBroadcast> liveBroadcastList = liveBroadcastListResponse.getItems();
if (liveBroadcastList != null && liveBroadcastList.size() > 0) {
LiveBroadcast liveBroadcast = liveBroadcastList.get(0);
String streamId = liveBroadcast.getContentDetails().getBoundStreamId();
// get livestream list
YouTube.LiveStreams.List livestreamRequest = mService.liveStreams().list("id,cdn");
livestreamRequest.setId(streamId);
LiveStreamListResponse liveStreamListResponse = livestreamRequest.execute();
List<LiveStream> liveStreamList = liveStreamListResponse.getItems();
if (liveStreamList != null && liveStreamList.size() > 0) {
LiveStream liveStream = liveStreamList.get(0);
String serverUrl = liveStream.getCdn().getIngestionInfo().getIngestionAddress();
String streamName = liveStream.getCdn().getIngestionInfo().getStreamName();
String rtmpUrl = serverUrl + "/" + streamName;
// use this rtmpUrl for streaming
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// call 30 seconds after press start streaming
private void checkStatus() {
try {
// get livebroadcast list
YouTube.LiveBroadcasts.List liveBroadcastRequest = mService.liveBroadcasts().list("id,snippet,contentDetails,status");
liveBroadcastRequest.setBroadcastType("persistent");
liveBroadcastRequest.setMine(true);
LiveBroadcastListResponse liveBroadcastListResponse = liveBroadcastRequest.execute();
List<LiveBroadcast> liveBroadcastList = liveBroadcastListResponse.getItems();
if (liveBroadcastList != null && liveBroadcastList.size() > 0) {
LiveBroadcast liveBroadcast = liveBroadcastList.get(0);
// get lifeCycleStatus
String lifeCycleStatus = liveBroadcast.getStatus().getLifeCycleStatus();
String recordingStatus = liveBroadcast.getStatus().getRecordingStatus();
if (lifeCycleStatus != null && lifeCycleStatus.equalsIgnoreCase("live") && recordingStatus != null && recordingStatus.equalsIgnoreCase("recording")) {
String videoId = liveBroadcast.getId();
// the url to watch is www.youtube.com/watch?v=videoId
// video is visible to audience
} else {
// the status is stuck at 'liveStarting', video is not visible to audience
// "status":{"lifeCycleStatus":"liveStarting","privacyStatus":"public","recordingStatus":"recording"}
// check the status of livestream
String boundStreamId = liveBroadcast.getContentDetails().getBoundStreamId();
YouTube.LiveStreams.List livestreamRequest = mService.liveStreams().list("id,cdn,status");
livestreamRequest.setId(boundStreamId);
LiveStreamListResponse liveStreamListResponse = livestreamRequest.execute();
List<LiveStream> liveStreamList = liveStreamListResponse.getItems();
if (liveStreamList != null && liveStreamList.size() > 0) {
LiveStream liveStream = liveStreamList.get(0);
String streamStatus = liveStream.getStatus().getStreamStatus();
if (streamStatus.equalsIgnoreCase("active")) {
// Log.e(TAG,"need to transite to live, liveBroadcastId = " + liveBroadcast.getId());
YouTube.LiveBroadcasts.Transition liveBroadcastTransitionRequest =
mService.liveBroadcasts().transition("live", liveBroadcast.getId(), "id,status");
LiveBroadcast liveBroadcastTransitionResponse = liveBroadcastTransitionRequest.execute();
// get error here
// error 403 Forbidden
// {
// "code" : 403,
// "errors" : [ {
// "domain" : "youtube.liveBroadcast",
// "message" : "Redundant transition",
// "reason" : "redundantTransition"
// } ],
// "message" : "Redundant transition"
// }
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// also try to create livebroadcast and live stream instead of the default one
private void createLiveBroadcast() {
try {
// step 1 create live broadcast
LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
broadcastSnippet.setTitle("Test live broadcast title");
Date currentTime = Calendar.getInstance().getTime();
broadcastSnippet.setScheduledStartTime(new DateTime(currentTime));
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("public");
// disable MonitorStreamInfo to change transition from ready to live
// refrence https://stackoverflow.com/questions/35003786/cannot-make-transition-of-my-youtube-broadcast-to-live-using-youtube-api
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
MonitorStreamInfo monitorStream = new MonitorStreamInfo();
monitorStream.setEnableMonitorStream(false);
contentDetails.setMonitorStream(monitorStream);
LiveBroadcast broadcast = new LiveBroadcast();
broadcast.setKind("youtube#liveBroadcast");
broadcast.setSnippet(broadcastSnippet);
broadcast.setStatus(status);
broadcast.setContentDetails(contentDetails);
YouTube.LiveBroadcasts.Insert liveBroadcastInsert =
mService.liveBroadcasts().insert("snippet,contentDetails,status", broadcast);
LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
// step 2 create live stream
String streamTitle = "Test Live Stream title";
LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
streamSnippet.setTitle(streamTitle);
CdnSettings cdnSettings = new CdnSettings();
cdnSettings.setFormat("720p");
cdnSettings.setIngestionType("rtmp");
LiveStream stream = new LiveStream();
stream.setKind("youtube#liveStream");
stream.setSnippet(streamSnippet);
stream.setCdn(cdnSettings);
YouTube.LiveStreams.Insert liveStreamInsert =
mService.liveStreams().insert("snippet,cdn", stream);
LiveStream returnedStream = liveStreamInsert.execute();
if (returnedStream != null) {
YouTube.LiveBroadcasts.Bind liveBroadcastBind =
mService.liveBroadcasts().bind(returnedBroadcast.getId(), "id,snippet,contentDetails,status");
liveBroadcastBind.setStreamId(returnedStream.getId());
returnedBroadcast = liveBroadcastBind.execute();
String serverUrl = returnedStream.getCdn().getIngestionInfo().getIngestionAddress();
String streamName = returnedStream.getCdn().getIngestionInfo().getStreamName();
String rtmpUrl = serverUrl + "/" + streamName;
// use this rtmpUrl for streaming
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Android AlarmManager Pass extra from activity to service

I have tried to follow many links but no matter what my extras keep being null. First I have an activity (MainActivity) that will set up a notification using a service (NotifyService). I can get the service to be and the notification to appear at the appropriate time. However passing a string seems to be a problem.
In MainActivity onCreate() I have:
Intent myIntent = new Intent(this, NotifyService.class);
//this is what I would like to pass over
myIntent.putExtra("newtitle" ,"this is the new title");
myIntent.putExtra("newcontent" ,"this is the new content");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 25);
calendar.set(Calendar.HOUR, 11);
calendar.set(Calendar.AM_PM, Calendar.PM);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(MainActivity.this, "Set Alarm", Toast.LENGTH_LONG).show();
In My NotifyService onCreate I have:
Intent intent = new Intent(this.getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
//this will be null or give me errors every time
// if (intent.getExtras().containsKey("newtitle"))
// title=(String) intent.getExtras().get("newtitle");
// if (intent.getExtras().containsKey("newcontent"))
// content=(String) intent.getExtras().get("newcontent");
NotificationCompat.Action action = new NotificationCompat.Action.Builder(
R.drawable.basketball, getString(R.string.wearTitle), pendingIntent
).build();
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(this)
.setContentText(content)
.setContentTitle(title)
.setSmallIcon(R.drawable.basketball)
.setSound(sound)
.extend(new NotificationCompat.WearableExtender().addAction(action))
.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(001, notification);
Mainly I've been following this tutorial: https://www.youtube.com/watch?v=tyVaPHv-RGo.
I've also looked at this link: How can I correctly pass unique extras to a pending intent?
I have tried many things with the PendingIntent flags but still no luck. I've seen it done with intents and services but nothing with pending intents.
Thanks a lot
Turns out instead on using it on create, I have to use onStartCommand. Here's the code:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();
Log.d("0",intent.getStringExtra("newtitle"));
title = intent.getStringExtra("newtitle");
content = intent.getStringExtra("newcontent");
Intent myintent = new Intent(this.getApplication(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,myintent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action = new NotificationCompat.Action.Builder(
R.drawable.basketball, getString(R.string.wearTitle), pendingIntent
).build();
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(this)
.setContentText(content)
.setContentTitle(title)
.setSmallIcon(R.drawable.basketball)
.setSound(sound)
.extend(new NotificationCompat.WearableExtender().addAction(action))
.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(001, notification);
return PendingIntent.FLAG_UPDATE_CURRENT; // or whatever your flag
}
Got it from: Pass data from Activity to Service using an Intent

Blank Message in Push Notification to Android Device Using GCM and Asp.net MVC Web API

I am using Asp.net MVC 4 Web API as a third party server to Push Notification for Android Device using GCM. It's working fine notification are being generated but the message is blank. I have spent whole day on it but could not find any solution please help me
Web API Function to Send Push Notification is as follows:
public Notification PushToAndroidDevice(string registrationid,string message)
{
Notification notification = new Notification();
try
{
var applicationID = "MY_APPLICATION_ID";
var SENDER_ID = "MY_SENDER_ID";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + message + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + registrationid + "";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
notification.Message = sResponseFromServer;
tReader.Close();
dataStream.Close();
tResponse.Close();
notification.Status = true;
}
catch (Exception ex)
{
notification.Status = false;
notification.Message = "ERROR DESCRIPTION : " + ex.Message;
}
return notification;
}
Notification is a class having two properties Status bool and Message string
public class Notification
{
public bool Status { get; set; }
public string Message { get; set; }
}
By this code I'm able to send notification message on android mobile but the notification is blank please help me out ...........
You shuould check the MSGReceiver and MSGSerice (or corresponding) class that receives the message from GCM server.
You check print and see if you are receiving null. May be the variable names used there and the one you are sending from your MVC are different. This is a very short answer. If you have further question or difficulty in undestanding then please provide relevant code and filenames.