My app's main functionality is push-notification messages sent from remote server. I am using FCM as a message delivery service. My problem is that notifications come without any sound on Xiaomi Mi 9 Lite (Android 9/MIUI 11). However, on Xiaomi Redmi Note 5 (Android 9/MIUI 10) sound works fine and on Samsung Galaxy S7 Edge (Android 8) as well. I created MessagingService which extends FirebaseMessagingService and notification channel as written in documentation.
Here is my code:
public class MessagingService extends FirebaseMessagingService {
private static String channelId;
private NotificationManager notificationManager;
private NotificationChannel notificationChannel;
private NotificationCompat.Builder notificationBuilder;
private MessagesViewModel viewModel;
public MessagingService() { }
#Override
public void onCreate() {
super.onCreate();
channelId = getResources().getString(R.string.default_notification_channel_id);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
final Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder = new NotificationCompat.Builder(this, channelId);
notificationBuilder.setSmallIcon(R.raw.metrial_message_icon);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setSound(soundUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
String name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableLights(true);
notificationChannel.setShowBadge(true);
notificationChannel.setSound(soundUri, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
notificationBuilder.setChannelId(channelId);
}
else {
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL);
notificationBuilder.setLights(Color.WHITE, 500, 5000);
}
viewModel = new MessagesViewModel(getApplication());
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
logger.info("onNewToken()");
ConnectionParameters.getInstance().setToken(s);
MyPrefs.getInstance(getApplicationContext()).putString(Constants.TOKEN, s);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
final String messageId = remoteMessage.getData().get("message_id");
final String title = remoteMessage.getData().get("title");
final String body = remoteMessage.getData().get("body");
if (messageId != null && title != null && body != null) {
final Message message = new Message();
message.setMessageId(messageId);
message.setTitle(title);
message.setContent(body);
message.setTimestamp(new Date());
try {
message.setNotificationId((int)viewModel.insert(message));
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
logger.info("onMessageReceived(): notificationId=" + message);
if (MyPrefs.getInstance(getApplicationContext()).getBoolean(Constants.ENABLE_PUSH)) {
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(body);
final Intent notifyIntent = new Intent(this, MessageInfoActivity.class);
notifyIntent.putExtra(Constants.ARG_MESSAGE_OBJECT, message);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(notifyIntent);
PendingIntent pendingActivityIntent =
stackBuilder.getPendingIntent(message.getNotificationId(), PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingActivityIntent);
final Notification notification = notificationBuilder.build();
notification.defaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS;
notificationManager.notify(message.getNotificationId(), notification);
}
}
}
private final Logger logger = LoggerFactory.getLogger(getClass());
}
And in Settings->Notifications I got the following parameters:
And inside my push-notifications-channel sound is enabled but whenever a message comes, it seems like app notification settings override parameters in notification channel.
There should be some solution because in popular apps such WhatsApp, Telegram, etc., these switches are enabled after installation (by default). Hope, someone helps!
As nobody provided better solution, I guess there is no way to allow sound/badge counter/floating notifications programmatically on MIUI (and mostly on other Chinese OEMs). It is a user's privilege to turn these settings on manually. Therefore, to enhance UX, it is important to decrease the quantity of "clicks" as much as possible. So, we could provide a dialog describing how to enable the features above with button leading to App's settings.
Namely, to open a notification settings page through Intent, do the following:
final Intent notificationSettingsIntent = new Intent();
notificationSettingsIntent
.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
notificationSettingsIntent
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationSettingsIntent.putExtra(
"android.provider.extra.APP_PACKAGE",
activity.getPackageName());
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationSettingsIntent.putExtra(
"app_package",
activity.getPackageName());
notificationSettingsIntent.putExtra(
"app_uid",
activity.getApplicationInfo().uid);
}
activity.startActivityForResult(
notificationSettingsIntent,
NOTIFICATIONS_SETTINGS_REQUEST_CODE);
and you could open a dialog with button "Open notification settings" clicking on which triggers the code snippet above.
Related
This question already has answers here:
How can we prevent a Service from being killed by OS?
(11 answers)
Background service stops after 20 sec after destroy app in Android 10 java
(1 answer)
Closed 1 year ago.
I am running audio player service but If I put my phone on sleep the player stops or the background service I don't know what's the problem.
this is my music service class :
public class MusicService extends Service {
public static final String ACTION_NEXT = "NEXT";
public static final String ACTION_PREV = "PREVIOUS";
public static final String ACTION_PLAY = "PLAY";
public static final String ACTION_FORWARD = "FORWARD";
public static final String ACTION_REWIND = "REWIND";
public static final String ACTION_CONTINUE = "CONTINUE";
ActionPlaying actionPlaying;
Action action;
private final IBinder mBinder = new MyBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class MyBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String actionName = intent.getStringExtra("myActionName");
if (actionName != null) {
switch (actionName)
{
case ACTION_PLAY:
if(actionPlaying!= null){
if(action!= null){
actionPlaying.playClicked();
action.playPauseClicked();
}}
break;
case ACTION_NEXT:
if(actionPlaying != null){
actionPlaying.nextClicked();
}
break;
case ACTION_PREV:
if(actionPlaying != null){
actionPlaying.prevClicked();
}
break;
case ACTION_FORWARD:
if(actionPlaying != null){
actionPlaying.forwardClicked();
}
break;
case ACTION_REWIND:
if(actionPlaying != null){
actionPlaying.rewindClicked();
}
break;
case ACTION_CONTINUE:
Toast.makeText(this, "continue", Toast.LENGTH_SHORT).show();
action.continueMediaPlayer();
}
}
return START_STICKY;
}
public void setCallBack(ActionPlaying actionPlaying){
this.actionPlaying = actionPlaying;
}
public void setCallBack(Action action) {
this.action = action;
}
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
notificationManager.cancelAll();
saveData();
simpleExoPlayer.release();
}
}
and this is my media player initialization :
public void prepareMedia() {
isPlaying=true;
simpleExoPlayer = new SimpleExoPlayer.Builder(MediaPlayer_Activity.this).build();
MediaItem mediaItem = MediaItem.fromUri(audioUrl);
simpleExoPlayer.addMediaItem(mediaItem);
simpleExoPlayer.prepare();
simpleExoPlayer.seekTo(songPrevPosition);
}
Please tell me what's wrong LogCat is not showing anything I don't know how to stop this and where the problem is....
please help
After 9 Android version we have protections for simple service. Simple service can live 10 seconds, no more. You need to declare you service as Foreground Service. It will look like notification in status bar.
For fully information read documentation
according to Android Developers documentation :
You need to upgrade your background process to foreground inorder to make it live without needing your application to be visible to the user.
in order to change your service to foreground one, your service need to have a notification to inform the user that your music player service is working.
a simple foreground service code might look like this :
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Notification notification = buildStartingNotification();
startForeground(startId, notification);
...
return START_STICKY;
}
private Notification buildStartingNotification() {
int priority =NotificationCompat.PRIORITY_LOW;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
priority = NotificationManager.IMPORTANCE_LOW;
createNotificationChannel(priority);
}
Notification notification =
new Notification.Builder(this,CHANNEL_ID)
.setContentTitle("Your_notification_title")
.setContentText("Your_notification_description ")
.setSmallIcon(R.drawable.icon)
.setPriority(priority)
.build();
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel(int priority) {
CharSequence name = getText("Your_Channel_Name");
String description = getString("Your_Channel_Desc");
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, priority);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
N.B : if you're using application with (target_api > 26) you need to have also a notification channel which I included its code in createNotificationChannel, where your CHANNEL_ID could be any unique string id you want.
if you're wandering what's the meaning of notification channel ?
a notification channel is a mechanism built for android 8 or later to make the user turn off/on group of notification with same channel at once from setting.
as an example your application might have multiple notification channels (news/games/entertainment...etc), then the user can turn off news &games and leave only entertainment on.
First of all make sure you use foreground service. I suggest to you to start permanent notification like this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationChannel channel;
Intent notifyIntent = new Intent(this, SomeActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = showStableMessage(this,
getString(R.string.app_desc),
"Message to user",
R.mipmap.ic_icon,
notifyPendingIntent);
startForeground(NotificationUtil.STABLE_CHANNEL_NOTIFY_ID, notification);
return Service.START_STICKY;
}
private Notification showStableMessage(Context context, String title, String message, int icon, PendingIntent intent) {
NotificationChannel channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(STABLE_CHANNEL_ID,
STABLE_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(context, STABLE_CHANNEL_ID)
.setContentTitle(title)
.setContentText(Html.fromHtml(message)).setPriority(PRIORITY_DEFAULT)
.setSmallIcon(icon)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(intent)
.setCategory(NotificationCompat.CATEGORY_SERVICE).build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
return notification;
}
Second you have to put this in manifest:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
.....>
<service
android:name=".data.service.MyService"
android:foregroundServiceType="mediaPlayback"
android:enabled="true"/>
</application>
I am currently writing a feature for my app that allows the user to make a request to the worker in which they can accept or decline the job offer. I am using firebase messaging system. When I have two phones, the notification works and the worker can accept or decline, stated here:
public class MyFirebaseMessaging extends FirebaseMessagingService {
private static final String COLE_CHANNEL_ID = "com.example.usub.COLE";
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
LatLng customer_location = new Gson().fromJson(remoteMessage.getNotification().getBody(),LatLng.class);
Intent intent = new Intent(getBaseContext(), CustomerCall.class);
intent.putExtra("lat", customer_location.latitude);
intent.putExtra("lng", customer_location.longitude);
intent.putExtra("customer", remoteMessage.getNotification().getTitle());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
However, I try to run the demo on my phone involving both apps, I receive the notification that the request has been made, however when the notification is clicked on, the app opens with no recollection of the data. My notification helper looks like this:
public class NotificationHelper extends ContextWrapper {
private static final String COLE_CHANNEL_ID = "com.example.usub.COLE";
private static final String COLE_CHANNEL_NAME = "STRADTMANNSOLUTIONS Usub";
private NotificationManager manager;
public NotificationHelper(Context base) {
super(base);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
createChannels();
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createChannels() {
NotificationChannel coleChannels = new NotificationChannel(COLE_CHANNEL_ID,
COLE_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
coleChannels.enableLights(true);
coleChannels.enableVibration(true);
coleChannels.setLightColor(Color.GRAY);
coleChannels.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(coleChannels);
}
public NotificationManager getManager() {
if(manager == null)
manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
return manager;
}
#RequiresApi(api = Build.VERSION_CODES.O)
public Notification.Builder getUsubNotification(String title, String content, PendingIntent contentIntent,
Uri soundUri)
{
return new Notification.Builder(getApplicationContext(),COLE_CHANNEL_ID)
.setContentText(content)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_notify);
}
}
Would anyone know why notification is losing all of its data or how I could open the app to a certain activity with new information from the press of a notification? Thank you
Notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If app is in the background then a notification is shown but it will not trigger onMessageRecieved, and data from that message is passed to the intent that is launched.
And u can use:-
getIntent().getExtras();
to retrieve the data sent via notification.
Check the docs this
I have an Activity where the user can download a video. Upon user's click, the Download Service starts to download the content.
There is a progress bar in the Activity UI which I would like to update according to download progress in the service which broadcasts the progress periodically.
Everything works fine but after a certain time the service stops sending any broadcast progress, hence, the UI does not update anymore.
Additionally, how I can resume receiving the progress broadcast when the user goes to another Activity and comes back to this Activity? I mean, even if the above issue is solved, when the user presses back button and go to other activity and comes back to this activity, the progress gets lots. How can I check for any existing broadcast and receive it whenever the user comes to this activity.
In the ACTIVITY:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.d("DownloadService", "Progress Received In Activity");
Double progress = bundle.getDouble("PROGRESS");
updateDownloadProgressBar(progress);
}
}
};
private void startDownloadService() {
final String videoId = mItem.getAttributes().get(KEY_ASSET_ID);
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("VIDEOID", videoId);
startService(intent);
}
in the onResume():
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION_SERVICE));
in the onPause():
unregisterReceiver(receiver);
In the SERVICE:
private void publishProgress(double progress) {
Log.d(TAG, "Broadcasting progress from Service");
Intent intent = new Intent(NOTIFICATION_SERVICE);
intent.putExtra("PROGRESS", progress);
sendBroadcast(intent);
}
The download and progress work fine to 38% then stop.
It seems that the service is being stopped/killed from the OS, to avoid that use foreground service so you can make sure it will not be killed from the OS.
See the sample code below:
Service
public class PendingService extends Service {
private final static String TAG = "PendingService";
public final static int NOTIFICATION_ID = 94;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startInForeground();
// Do your work here ...
return START_STICKY;
}
private void startInForeground() {
String NOTIFICATION_CHANNEL_ID = "default";
String NOTIFICATION_CHANNEL_NAME = "My Pending Service";
String NOTIFICATION_CHANNEL_DESC = "This notification holding a pending task";
Intent notificationIntent = new Intent(this, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
channel.setSound(null, null);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
Notification notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
removeNotification(NOTIFICATION_ID);
// ....
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void removeNotification(int notificationId) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(notificationId);
}
}
}
Utils you may need
class ServiceUtils {
/**
* #param service: Service to run
*/
fun startService(context: Context, service: Class<out Service>) {
val serviceIntent = Intent(context, service)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
}
/**
* #return True: if the service is running
*/
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}
I'm building a VoIP app on React Native, which detects incoming calls using push notifications. I need to start the app and bring it to the foreground on receiving a push notification. I'm able to achieve that for the following scenarios:
When the device is unlocked and:
The app is minimized (is still in the background)
The app is not in the background (killed from multitasking view)
When the device is locked and:
The app is minimized (is still in the background)
The only scenario I'm not able to handle is when the device is locked and the app is killed. The app starts but does not show up over the lock screen. Instead, the user needs to unlock the phone to access the app.
Here's the piece of code that runs when a notification is received,
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent notificationIntent = new Intent(this, MainActivity.class);
// Check if app is running
if(MainActivity.isAppRunning) {
startActivity(notificationIntent);
Intent messagingEvent = new Intent(MESSAGE_EVENT);
messagingEvent.putExtra("message", remoteMessage);
// Broadcast it so it is only available to the RN Application
LocalBroadcastManager
.getInstance(this)
.sendBroadcast(messagingEvent);
} else {
startActivity(notificationIntent);
try {
// If the app is in the background we send it to the Headless JS Service
Intent headlessIntent = new Intent(
this.getApplicationContext(),
BackgroundListenService.class
);
headlessIntent.putExtra("message", remoteMessage);
this
.getApplicationContext()
.startService(headlessIntent);
Log.d(TAG, "message: " + remoteMessage);
HeadlessJsTaskService.acquireWakeLockNow(this.getApplicationContext());
} catch (IllegalStateException ex) {
Log.e(
TAG,
"Background messages will only work if the message priority is set to 'high'",
ex
);
}
}
}
And here's my MainActivity:
public class MainActivity extends NavigationActivity {
public static boolean isAppRunning;
private static boolean isMessageRecieved;
private class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
isMessageRecieved=true;
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this);
super.onCreate(savedInstanceState);
isAppRunning = true;
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
// Subscribe to message events
localBroadcastManager.registerReceiver(
new MainActivity.MessageReceiver(),
new IntentFilter(MyFirebaseMessagingService.MESSAGE_EVENT)
);
if(isMessageRecieved) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "1";
String channel2 = "2";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
isAppRunning = false;
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
}
How to get full content of notification in Lolipop or above devices.
I am unable to get notification detail like buttons and icons in notification with this.
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker ="";
if(sbn.getNotification().tickerText !=null) {
ticker = sbn.getNotification().tickerText.toString();
}
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgs = new Intent("Msg");
msgs.putExtra("package", pack);
msgs.putExtra("ticker", ticker);
msgs.putExtra("title", title);
msgs.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgs);
}
As I have seen you did not create your notification. You need a notification builder just after your notification is received in your application.
Hence in the receiver of your broadcast, you need to create the notification to be shown in your status bar like the following.
// Inside your broadcast receiver
int notificationID = new Random().nextInt();
Intent intent = new Intent(mContext, YourHomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, notificationID, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext)
.addAction(R.drawable.ic_prev, "BUTTON 1", myIntentToButtonOneScreen)
.addAction(R.drawable.ic_pause, "BUTTON 2", myIntentToButtonTwoScreen) // #1
.addAction(R.drawable.ic_next, "BUTTON 3", myIntentToButtonThreeScreen)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
if (result != null)
notificationBuilder.setLargeIcon(result);
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationID, notificationBuilder.build());
This is just a sample code which might not work. But this is just to give you an idea. Please follow this developer documentation for better understanding.
Update
Based on the comment asking for the notification listener service, here's sample code on how you can listen to notification that was sent to your mobile. Considering you have used Firebase cloud messaging.
public class FCMListenerService extends FirebaseMessagingService {
private FCMNotificationResponse mFcmNotificationResponse;
private RemoteMessage.Notification notification;
private Map data;
private String from;
#Override
public void onMessageReceived(RemoteMessage message) {
parseRemoteMessage(message);
}
private void parseRemoteMessage(RemoteMessage message) {
from = message.getFrom();
data = message.getData();
notification = message.getNotification();
Logger.logD("Message", "From: " + from);
// Check if message contains a data payload.
if (data.size() > 0) {
Logger.logD("Data", "Message data payload: " + data.toString());
setNotificationResponseFromData(data);
}
createNotification(this, notification.getTitle(), notification.getBody(), mFcmNotificationResponse.getIcon());
}
// Here you parse the JSON body received from notification
private void setNotificationResponseFromData(Map data) {
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(data);
mFcmNotificationResponse = gson.fromJson(jsonElement, FCMNotificationResponse.class);
}
private void createNotification(Context context, String title, String message, String imageUrl) {
new CreateNotificationAsyncTask(context, title,
message, imageUrl).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
onMessageReceived function is called when a notification is received. Then you need to parse your data and then create the notification accordingly.