I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.
Code:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
You can use this method. Now with latest API versions you need to set channel for notifications.
private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
int icon = R.mipmap.icon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
icon = R.mipmap.icon_transparent;
}
Intent notificationIntent = new Intent(this, CurrentActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.setContentTitle("Service")
.setContentText("Running...");
Notification notification=builder.build();
if(Build.VERSION.SDK_INT>=26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
.setContentTitle("Service")
.setContentText("Running...")
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.build();
}
startForeground(121, notification);
}
Related
I have been trying to create an incoming call type notification for my Android app, written in native Java code, and in many resources online I have read that using the .setOngoing(true) tag on the NotificationBuilder would be enough to have the desired behaviour of the notification being visible, playing the ringtone sound until it is clicked, but that has not worked for me.
I have also tried using the flags Notification.FLAG_INSISTENT and Notification.FLAG_NO_CLEAR without success.
Here is my current code:
private void ringtone(Context context){
String channelId = "call_channel";
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Incoming Call")
.setContentText("You have an incoming call")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(contentIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence channelName = "Incoming Calls";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableVibration(true);
long[] pattern = {0, 1000, 500, 1000};
notificationChannel.setVibrationPattern(pattern);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setLegacyStreamType(AudioManager.STREAM_RING)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationChannel.setAllowBubbles(true);
}
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setSound(ringtoneUri,att);
notificationManager.createNotificationChannel(notificationChannel);
}else{
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
notification.flags |= Notification.FLAG_INSISTENT | Notification.FLAG_NO_CLEAR;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
My intention is to have an incoming call type of notification much like other applications such as MS Teams, Whatsapp, ETC. and my issue is that the notification gets minimized after showing on screen for a few seconds, and the ringtone stops shortly after. Thank you for any help with this.
I am building an android application which push notification in specific times and this working well for me and notification received at these times but I want to turn on screen when Notification received.
I searched for that and I found all answers use PowerManager.FULL_WAKE_LOCK which is deprecated now so I need new way for this, How can I do that ?
this is my Notification code
public void ShowNotification(String title, String message, Class acticity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, "my app",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID);
builder.setSmallIcon(R.drawable.notif)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setAutoCancel(true);
Intent intent = new Intent(context, acticity);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.putExtra("clicked", true);
PendingIntent pi = PendingIntent.getActivity(context, 99,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);
Uri sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound);
mp = MediaPlayer.create(context, sound);
mp.start();
mcompact.notify(99, builder.build());
}
Is it possible to return to previous application from where your application is opened?
For example I am in application A then I click on notification and open my application B then in my application B I click a button and I get back to application A? Currently I am trying to do that and the only way how I achieved is when my application is running in background or it only works for the first time.
I am using Flutter but these actions are executed in native Android code so I am probably missing something.
For getting back to previous app I am using:
moveTaskToBack(true);
For creating a notification my code looks like this:
private void NotifyToAutofill(String uri, String url, NotificationManager notificationManager) {
if (notificationManager == null || isNullOrWhitespace(uri)) {
return;
}
Context context = getApplicationContext();
Intent startIntent = new Intent(context, MainActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startIntent.setAction(Intent.ACTION_RUN);
startIntent.putExtra("uri", uri);
startIntent.putExtra("url", url.contains("\u2022")
|| url.contains("\u2731") ? "" : url);
String channelId = "channel-01";
String channelName = "test";
int importance = NotificationManager.IMPORTANCE_LOW;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
int color = 0x008000;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Test Service")
.setContentText("Tap to open application")
.setAutoCancel(true);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(startIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(AutoFillNotificationId, notification);
}
Found the solution. My problem was that i was creating PendingIntent with
stackBuilder.addNextIntent(startIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Everything worked as intented when I used:
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);
After upgrading my app target api to 27 notification is no more working and i get a toast message on android studio emulator:
Failed to post notification on channel “null”
Here is my notification code:
private void sendNotification(Context context, String sysModel) {
Intent intentAction = new Intent(context, MainActivity.class);
intentAction.putExtra("sysModel", sysModel);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intentAction, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.changer_ico)
.setContentTitle(context.getString(R.string.service_ready))
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
.setAutoCancel(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(1903, notification);
}
Can you test the code below?
Note that new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL); instead of new NotificationCompat.Builder(context);
private final static String NOTIFICATION_CHANNEL = "channel_name";
private final static String CHANNEL_DESCRIPTION = "channel_description";
public final static int NOTIFICATION_ID = 1903;
private void sendNotification(Context context, String sysModel) {
// Intent
Intent intentAction = new Intent(context, MainActivity.class);
intentAction.putExtra("sysModel", sysModel);
// Pending Intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intentAction, PendingIntent.FLAG_ONE_SHOT);
// Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
// Create the notification channel if android >= 8
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, CHANNEL_DESCRIPTION, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
// Notification builder.. Note that I added the notification channel on this constructor
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL);
notificationBuilder.setSmallIcon(R.drawable.changer_ico)
notificationBuilder.setContentTitle(context.getString(R.string.service_ready))
notificationBuilder.setContentIntent(pendingIntent)
notificationBuilder.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
notificationBuilder.setAutoCancel(true);
// Notify
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
In android O you should dispatch notice like follow:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.changer_ico)
.setContentTitle(context.getString(R.string.service_ready))
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_key_black_24dp, context.getString(R.string.turn_on), pendingIntent)
.setAutoCancel(true);
Notification notification = notificationBuilder.build();
NotificationChannel channel = new NotificationChannel("1903",
context.getString(R.string.user_notify), NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
notificationManager.notify(1903, notification);
When I click on the notification that pops up it doesn't open BaseApplication.class. What am I doing wrong here? I want the notification to open BaseApplication.class
public static void sendBasicNotification(int minor, int major, String task) {
Intent notifyIntent = new Intent(currentContext, BaseApplication.class);
notifyIntent.putExtra("t", task);
notifyIntent.putExtra("ma", major);
notifyIntent.putExtra("mi", minor);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(currentContext, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
int notificationID = 21;
NotificationCompat.Builder builder = new NotificationCompat.Builder(currentContext)
.setContentText("You have started the task: " + task).setContentTitle("Task Alert")
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis()).setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.getNotification();
NotificationManager notificationManager = getNotificationManager(currentContext);
notificationManager.notify(notificationID, notification);
}
static NotificationManager getNotificationManager(Context context) {
return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Turns out I was sending the intent to the wrong class. Thanks all, fixed now. That code works just fine.
try adding this line
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_SINGLE_TOP);
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// MainActivity is the Notification Intent that open by intent
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Application name")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
hope it will work