GCM Notification Title and Message in LockScreen (Android) - notifications

I want to show a GCM Notification containing a title, message, and a large icon in the Lock Screen. The image and the title will be coming from my app where the title is my app's name and the notification belong to one signal service.
I want to make the notification same as below notification in the picture.
This is my code:
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
GcmBroadcastReceiver.completeWakefulIntent(intent);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Bitmap small_Icon = getBitmapFromURL((String) extras.get(Config.SMALLICON_KEY));
Bitmap large_Icon = getBitmapFromURL((String) extras.get(Config.LARGEICON_KEY));
Bitmap Poster = getBitmapFromURL((String) extras.get(Config.BIGPICTURE_KEY));
String title = (String) extras.get(Config.TITLE_KEY);
String message = (String) extras.get(Config.MESSAGE_KEY);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon((R.drawable.ic_launcher))
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(Poster)
.setBigContentTitle(title)
.setSummaryText(message))
.setContentTitle(title)
.setContentText(message)
.setLargeIcon(large_Icon);
//////// Play Defult Notification Sound ////////
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
//////// End Play Defult Notification Sound ////////
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}

What you are aiming to do is a visible Lock Screen Notification. As per the docs:
Setting Visibility
Your app can control the level of detail visible in notifications displayed on a secure lock screen. You call setVisibility() and specify one of the following values: VISIBILITY_PUBLIC, VISIBILITY_SECRET, VISIBILITY_PRIVATE.
Also found this Simple Tutorial on Lollipop Notifications that might be useful for you.

Related

Convert text and current background image of recyclerview to image and save it to device

in my adapter i have add this code
holder.binding.saveButton.setOnClickListener {
mediaPlayer.start()
if (ContextCompat.checkSelfPermission(holder.itemView.context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(holder.itemView.context as Activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_WRITE_STORAGE)
} else {
val parentView = holder.itemView.findViewById<LinearLayout>(R.id.itemViewe)
parentView.isDrawingCacheEnabled = true
val bitmap = parentView.getDrawingCache()
// Create a file to save the image
val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile("your_image_name", ".jpg", imagesDir)
// Compress the bitmap and save it to the file
val stream = FileOutputStream(image)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
stream.flush()
stream.close()
// Clear the drawing cache
parentView.destroyDrawingCache()
// Add the image to the system gallery
val values = ContentValues()
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.MediaColumns.DATA, image.absolutePath)
holder.itemView.context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
// Show a toast message to indicate that the image has been saved
Toast.makeText(holder.itemView.context, "Status Saved", Toast.LENGTH_SHORT).show()
}
}
when click on save button in recyclerview show permisiion to allow and after show toast status saved but in gallery its not showing ..... in my case my device android version 11 so image show in gallery but in version 12 when save button clicked show toast and show blank in gallery not full image.
it work on some version and not work in other versions but i want to work it for all device how can i do it

BigTextStyle doesn't work when used with BigPictureStyle in notification (Kotlin)

When I use BigTextStyle and BigPictureStyle together, only setContentText and BigPictureStyle are shown in the notification drawar. I mean if the text is long, it won't show the full text (BigTextStyle doesn't seem to work at all)
It shows the same on my phone (Android 11),
Does anyone know how I can solve this problem?
private fun sendNotification() {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val bitmap = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.wallet)
val bitmapLargeImage = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.sell)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_attach_money_24)
.setContentTitle("Purchase")
.setContentText("This is the text I want to show to my users in the notification bar, but it is not fully shown.")
.setContentIntent(pendingIntent)
.setStyle(NotificationCompat.BigTextStyle().bigText("This is the text I want to show to my users in the notification bar, but it is not fully shown."))
.setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmapLargeImage))
.setLargeIcon(bitmap)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(this)) {
notify(notificationID, builder.build())
}
}
Wanted to post a comment but don't have enough reputation.
As far as I know you cannot use BigTextStyle with BigPictureStyle, by default.
To do that, you need to create a Custom View for your notification
See the documentation on how to create a Custom View for a notification: https://developer.android.com/training/notify-user/custom-notification
Maybe this similar stackoverflow question can help: How to use both BigTextStyle and BigPictureStyle in setStyle Notification?
While this may not be a problem for you, for apps that target Android 12 some behaviours for fully custom notifications change - See https://developer.android.com/about/versions/12/behavior-changes-12#custom-notifications

smallIcon is round grey blob when using actual payload of remoteMessage.notification.body

I'm seeing odd behavior with the smallIcon being a displayed as grey circle when I attempt to use the actual String received in the payload of the RemoteMessage. When I hard code it the smallIcon displays properly.
Tried moving the order of things I'm setting in builder which didn't impact it. Also tried to set the String vs. String? to the value in remoteMessage.notification.body
private fun sendNotification(remoteMessage: RemoteMessage?) {
if (remoteMessage?.notification != null) {
// Setup Intent to Open Home
val intent = Intent(this, Home::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)
// Parse the remoteMessage
val body : String? = remoteMessage.notification?.body
var builder = Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notify_icon_small_white)
.setColor(Color.parseColor(bgColor))
.setContentIntent(pendingIntent)
.setContentTitle("strive.ai")
.setContentText(body)
with(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) {
val notificationId = getNextNotificationId(applicationContext)
notify(notificationId, builder.build())
Log.d(TAG, "sendNotification($notificationId)")
}
}
}
I was able to get this working by using the Manifest File settings instead of using code to affect the icon and color to use.
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />

setOngoing(true) is not working in Oreo+ Notifications

I am creating a custom notification with channel_id and start it as foreground. I have background music playing .. My problem is when user swipe notification it disappears. I have also setOngoing(true). i want notification to stay when music is playing.
NOTE: It only happens in Oreo+. in lower versions it is working fine.
public void CustomNotification() {
remoteViews = new RemoteViews(getPackageName(), R.layout.player_noti_layout);
notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
getString(R.string.player_channel),
NotificationManager.IMPORTANCE_LOW);
channel.enableVibration(true);
channel.enableLights(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setDescription("Notification, Play/pause & Next/Prev");
notificationmanager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(this, "default");
Notification foregroundNote;
// Set icon
foregroundNote = builder.setSmallIcon(R.drawable.ic_radio)
.setLargeIcon(R.drawable.cool_1)
// Set ticker message
.setTicker(getResources().getString(R.string.app_name))
// Dismiss notification
.setAutoCancel(false)
.setOngoing(true)
.setContent(remoteViews)
.setContentTitle("title").
setContentText("text")
.build();
foregroundNote.flags |= Notification.FLAG_ONGOING_EVENT;
foregroundNote.flags |= Notification.FLAG_NO_CLEAR;
foregroundNote.contentView = remoteViews;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
startForeground(2, foregroundNote);
} else
notificationmanager.notify(2, foregroundNote);
}
In a few words, that's due to fragmentation and customization. Probably that phone has some kind of setting to configure that behavior. As someone said one day: Some phones are just -trash-. Don't waste your time trying to fix an issue for every possible phone.

How to do MediaCapture in UWP application but not store in local machine

I am developing an UWP application with a camera feature, I have studied this sets of codes,
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/CameraStarterKit
And successfully developed a camera feature on my application. However, in my application, I wish to not store the picture into my local machine as the application is actually like a kiosk system whereby everyone will be using the same machine to take the picture.
What I am planning to do is actually to allow users to send the picture that they have taken to their own email address via the kiosk system. When they have taken a photo, a preview will be shown, and only if the user want to send the picture, then will the picture be "save"
The codes for my take photo function is something like this:
rivate async Task TakePhotoAsync()
{
var stream = new InMemoryRandomAccessStream();
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Photo taken! Saving to " + file.Path);
var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());
await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
Debug.WriteLine("Photo saved!");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
}
}
And to get the preview of the picture will be:
private async Task GetPreviewFrameAsSoftwareBitmapAsync()
{
// Get information about the preview
var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
// Create the video frame to request a SoftwareBitmap preview frame
var videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);
// Capture the preview frame
using (var currentFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame))
{
// Collect the resulting frame
SoftwareBitmap previewFrame = currentFrame.SoftwareBitmap;
// Show the frame information
FrameInfoTextBlock.Text = String.Format("{0}x{1} {2}", previewFrame.PixelWidth, previewFrame.PixelHeight, previewFrame.BitmapPixelFormat);
// Create a SoftwareBitmapSource to display the SoftwareBitmap to the user
var sbSource = new SoftwareBitmapSource();
await sbSource.SetBitmapAsync(previewFrame);
// Display it in the Image control
PreviewFrameImage.Source = sbSource;
}
}
There are (at least) two ways:
1) "Better" one:
Create a backend that sends email using SmtpClient
Post your image from UWP to backend using HttpClient
2) "Easier" one: launch Mail app
The downside is that users will be able to edit the message, receiver and things like that.
Also you can try to use SmtpClient directly from UWP client (may be now with .Net Standard 2.0 it would be possible but I guess no one yet tried) or third-party open-source replacement (which might be a bit outdated as it was created for Windows 8) or even try to launch your backend as Windows Service on the client machine.