My Notification Channel is not being created - java

Whenever I send a notification through fcm.
It says it will use the default from manifest or the android app, I also have mentioned my channel in manifest as default.
It just says that the channel is not created by the app.
Log says
W/FirebaseMessaging: Notification Channel requested (message_notification) has not been created by the app. Manifest configuration, or default, value will be used.
This is my onMessageReceived function.
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+":/ /"+applicationContext.packageName+"/"+R.raw.alert)
Log.d("notofiction Nul", sound.toString())
if(p0.notification!=null){
val title = p0.data["title"]
val message = p0.data["body"]
Log.d("notottg",title+message)
buildNotificationChannel()
if(buildNotificationChannel()){
generateNotification(title!!,message!!)
}
}
else{
val title = p0.data["title"]
val message = p0.data["body"]
Log.d("notottg",title+message)
buildNotificationChannel()
if(buildNotificationChannel()){
generateNotification(title!!,message!!)
}
}
}
This is my createNotificationChannel function
private fun buildNotificationChannel():Boolean {
/*var audioAttributes = AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+applicationContext.packageName+"/"+R.raw.alert)
Log.d("notisound",sound.toString())*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val CHANNEL_ID = "merchant_notification"
val CHANNEL_NAME = "Merchant Notification"
var notificationChannel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
vibrationPattern=longArrayOf(400, 400, 400, 400, 500, 400, 400, 400, 400)
enableVibration(true)
}
notificationManager= getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
//notificationChannel.setSound(sound,audioAttributes)
}
return true
}
And this is my generateNotification function
fun generateNotification(title: String, message: String) {
val intent = Intent(this#CustomMessagingService, MainActActivity::class.java)
var pendingIntent = PendingIntent.getActivity(this#CustomMessagingService, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var builder: NotificationCompat.Builder =
NotificationCompat.Builder(this, "merchant_notification")
var audioAttributes = AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+applicationContext.packageName+"/"+R.raw.alert)
Log.d("notisound",sound.toString())
builder.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setSound(sound)
notification = builder.build()
Log.d("notot", notification.toString() + " " + sound.toString())
notificationManager.notify(1, notification)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
var nb: Notification.Builder = Notification.Builder(this)
nb.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(true)
.setSound(sound, audioAttributes)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.build()
notification = nb.notification
notification.flags = Notification.FLAG_AUTO_CANCEL
notificationManager.notify(0, notification)
}
}
My Manifest Code
<service android:name=".classes.CustomMessagingService"
android:exported="false"
android:enabled="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"
/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="merchant_notification" />

It works for me:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // channel for notifications
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
List<NotificationChannel> channelList = notificationManager.getNotificationChannels();
for (int i = 0; channelList != null && i < channelList.size(); i++)
notificationManager.deleteNotificationChannel(channelList.get(i).getId());
}
String name = getString(R.string.notification_channel_name);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(getString(R.string.notification_channel_id), name, importance);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
Intent intent;
intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.notification_channel_id))
.setSmallIcon(R.drawable.logo)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentTitle(message.getData ().get ("myBody"))
.setContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());
}
#Override
public void onNewToken(#NonNull String token) {
}
}
Manifest:
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/notification_channel_id" />

Related

Firebase message not opening application when clicking on the notification

I added the following pice in the manifest to call the onMessageReceived function when a firebase message comes in:
<service android:name=".Notifications"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Here is my onMessageReceive function:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("NotificationService", "Notification received!");
Map<String, String> data = remoteMessage.getData();
String deep_link = data.get("deep_link");
String title = data.get("title");
String body = data.get("body");
Log.d("NotificationService", "Notification received!");
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.context.getApplicationContext(), "1");
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(new MainActivity(), Uri.parse(deep_link));
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle(title);
builder.setContentText(body);
NotificationManager notificationManager = (NotificationManager) MainActivity.context.getSystemService(MainActivity.context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "1";
NotificationChannel channel = new NotificationChannel(
channelId,
"1",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
But the function is never called does someone know where the problem lays?
I tried to send the notification with and without notification payload, tried the app in background state and foreground state, tried killing the app and then sending the notification
When clicking the notification it doesnt open the app or anything

Notification Builder action not working on API 31 (Android 12)

I'm stuck while dealing with this api 31. i made a chat app. When I create an action button to receive a phone call it works on android below API 31 or below Android 12, but it doesn't work on Android 12 (only work if the notification is not has action). maybe someone here can help me in finding a solution to this problem?
FirebaseService.java
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
boolean cancelNotification = false;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Map<String, String> params = remoteMessage.getData();
JSONObject data = new JSONObject(params);
PendingIntent pendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
}
else {
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
}
String channel_id = getNotificationData(data, "channel");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel_id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getNotificationData(data, "title"))
.setContentText(getNotificationData(data, "body"))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("open")){
playCallSound(this);
if(WindowUtil.isAppOnBackground(this) || isScreenOff()){
ArrayList<String> par = new ArrayList<>();
par.add("call_channel");
par.add("call_type");
par.add("call_token");
par.add("call_peer");
String callType = getNotificationData(data, "call_type");
if(callType.equals("3") || callType.equals("4")){
par.add("call_group_name");
par.add("call_group_caller");
}
Intent receiveCallAction = new Intent(this, CallReceiver.class);
receiveCallAction.putExtra("action", "ANSWER");
Intent cancelCallAction = new Intent(this, CallReceiver.class);
cancelCallAction.putExtra("action", "DECLINE");
for (String s : par) {
receiveCallAction.putExtra(s, getNotificationData(data, s));
cancelCallAction.putExtra(s, getNotificationData(data, s));
}
notificationBuilder.setOngoing(true);
receiveCallAction.setAction("RECEIVE_CALL");
cancelCallAction.setAction("CANCEL_CALL");
PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder
.addAction(R.drawable.ic_baseline_call_24_green, "Answer", receiveCallPendingIntent)
.addAction(R.drawable.ic_baseline_call_red_24, "Decline", cancelCallPendingIntent);
}else{
cancelNotification = true;
}
}if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("end_timeout")){
stopRinging();
}else if(channel_id.equals("ntf1")){
if(UserUtil.IS_CHAT_ACTIVITY){
cancelNotification = true;
}
if(!cancelNotification){
playNotificationSound(this);
}
}
if(!cancelNotification){
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
NotificationChannel channel = new NotificationChannel(channel_id,
getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.enableVibration(true);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(1000, notificationBuilder.build());
}
}
CallReceiver.java (Broadcast Receiver)
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getExtras() != null) {
String action = intent.getStringExtra("action");
// Perform the action
performClickAction(context, action, intent.getExtras());
// Close the notification after the click action is performed.
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1000);
// Stop the ringtone
stopRinging();
}
}
on my AndroidManifest.xml
<service
android:name=".services.FirebaseService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<receiver
android:name=".receiver.CallReceiver"
android:exported="false"
android:enabled="true">
<intent-filter>
<action android:name="CALL_RECEIVER" />
</intent-filter>
</receiver>
Thank you
i solve this problem by this code
PendingIntent receiveCallPendingIntent;
PendingIntent cancelCallPendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
}else{
receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
}
also add this permission for force Android 12^ (AndroidManifest.xml)
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><receiver
android:name=".receiver.CallReceiver"
android:exported="false"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

ANDROID STUDIO- Service not working when device disconnected to power

I have a problem and that is that the service I use in an Android project does not work when I disconnect the device from the power. If it is connected, it does work. I have tried many alternatives and the last thing I tried is this.
I need help... anything that can solve this problem?
Android Manifest and Service
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.resolucion.probando" >
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Probando" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SegundaActivity"></activity>
<service android:process=":remote" android:name=".NuevoIntento"></service>
</application>
</manifest>
public class NuevoIntento extends Service {
private ScheduledExecutorService scheduleTaskExecutor;
private Context context;
TextView tv;
int hora;
int minutos;
int seconds;
int minutosumado;
#Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "Service binding");
return null;
}
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
setNotification();
if (scheduleTaskExecutor == null) {
scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new mainTask(), 0, 10, TimeUnit.SECONDS);
}
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_main, null);
tv = layout.findViewById(R.id.hora);
return Service.START_STICKY;
}
public void setNotification() {
PendingIntent contentIntent;
contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MainActivity")
.setSmallIcon(R.drawable.ic_launcher_background)
.setColor(this.getResources().getColor(R.color.black))
.setOngoing(true)
.setAutoCancel(false)
.setContentText("MyApp");
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(101, mBuilder.build());
Notification notification = mBuilder.build();
startMyOwnForeground(); //NOTIFICATION_ID is a random integer value which has to be unique in an app
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
private class mainTask implements Runnable {
public void run() {
Log.e("TAG","TAG");
}
}
}

Notification head's up and sound not working in android O and hinger

I have been trying to get sound and (heads up/pop up) on my notification but nothing is working I read a lot of questions on SO related to this issue and even implement most of them but nothing is working. The only thing which is working with the notification tell yet is its vibration.
Here is my notification channel (in app class)
Im trying to get sound and heads up on channel2
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_FOR_SERVICE,
utilityClass.NOTIFICATION_CHANNEL_NAME_FIRST, NotificationManager.IMPORTANCE_LOW);
NotificationChannel channel2 = new NotificationChannel(CHANNEL_ID_FOR_REMINDER,
utilityClass.NOTIFICATION_CHANNEL_NAME_SECOND, NotificationManager.IMPORTANCE_HIGH);
channel2.enableVibration(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel2.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,audioAttributes);
channel2.setVibrationPattern(new long[]{300, 300, 300});
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
manager.createNotificationChannel(channel2);
}
}
And here I'm creating notification
Intent intent = new Intent(getApplicationContext(), MarkNotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), (int) currentTime, intent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_FOR_REMINDER)
.setSmallIcon(R.drawable.ic_baseline_bookmark_border_24)
.setContentTitle("Title")
.setWhen(System.currentTimeMillis())
.setPriority(NotificationCompat.PRIORITY_MAX)
.addAction(R.drawable.ic_baseline_bookmark_border_24, "Reminder", pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) currentTime, notification);
EDIT: If I manually give floating notification permission in system app sitting then it works fine (heads up)
Add these permissions
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
2.Add build method
public NotificationCompat.Builder createBuilder(Context context
, NotificationManagerCompat manager) {
String channelId = context.getPackageName();
NotificationCompat.Builder notBuilder = new NotificationCompat
.Builder(context, channelId);
notBuilder.setSmallIcon(R.drawable.ic_stat_name);
notBuilder.setColor(Color.parseColor("#3580FF"));
notBuilder.setAutoCancel(true);
notBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND);
notBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notBuilder.setSound(soundUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId
, "Notifications",
NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
channel.shouldShowLights();
channel.setLightColor(Color.BLUE);
channel.canBypassDnd();
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(soundUri, audioAttributes);
channel.setDescription("Notifications");
notBuilder.setChannelId(channelId);
manager.createNotificationChannel(channel);
}
return notBuilder;
}
3.Show notification
NotificationManagerCompat manager=NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = createBuilder(
context, manager);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setCategory(NotificationCompat.CATEGORY_NAVIGATION);
Intent parentIntent = new Intent(context, ActHome.class);
parentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(context
, NOTIFICATION_ID, parentIntent, PendingIntent.FLAG_ONE_SHOT |
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
manager.notify(NOTIFICATION_ID, builder.build());
4.If still doesn't work Uninstall and reinstall the app

Why do I have to double click by a notification to close it when my app was closed?

I'm creating a ClockApp for Android. I have AlarmBroadcastReceiver which gives me a notification with the button close alarm and when an user clicks by that button the notification will be disappeared. However, it doesn't work when my app was closed. For example, I set alarm at 7:00 am and I closed my app then I waked up and I found on my phone a notification close alarm I clicked by that button but I just was redirected to a main activity then I clicked again and only then the notification will be disappeared. Why do I have to click two times? However, if my app isn't closed I have to click only one time and the notification will be disappeared. I hope you'll help me with my problem)
Code: (I have MainActivity with tabs)
MainActivity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// cancel notifications
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (intent.getBooleanExtra("alarm_cancel_notification", false)) {
if (notificationManager != null) {
notificationManager.cancel(1);
}
}
}
AlarmFragment:
private void startAlarm() {
Intent intent = new Intent(getContext(), AlarmManagerBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getContext(),
1,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= 23) {
AlarmManager.AlarmClockInfo alarmClockInfo =
new AlarmManager.AlarmClockInfo(mCalendar.getTimeInMillis(), pendingIntent);
mAlarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
}
}
BroadcastReceiver:
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static final int ALARM_EXPIRED_NOTIFICATION_ID = 1;
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("alarm_cancel_notification", true);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(
context.getPackageName(),
R.layout.partial_notification);
remoteViews.setTextViewText(
R.id.cancel_button_notification,
context.getString(R.string.alarm_notification));
remoteViews.setOnClickPendingIntent(
R.id.cancel_button_notification,
notificationPendingIntent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context,
ChannelIdApp.CHANNEL_ID);
builder.setAutoCancel(true)
.setTicker("Alarm")
.setCustomContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setSmallIcon(R.drawable.ic_stat_notify_clock);
Notification notification = builder.build();
notification.flags = notification.flags | Notification.FLAG_INSISTENT;
if (notificationManager != null) {
notificationManager.notify(ALARM_EXPIRED_NOTIFICATION_ID, notification);
}
}
}
Channel Id:
public class ChannelIdApp extends Application {
public static final String CHANNEL_ID = "clock_channel_id";
#Override
public void onCreate() {
super.onCreate();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID,
"Clock notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableVibration(true);
notificationChannel.enableLights(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
}
Manifest:
<activity
android:launchMode="singleTop"
android:name=".activities.MainActivity"
android:screenOrientation="portrait" />
<receiver
android:exported="false"
android:name=".AlarmManagerBroadcastReceiver" />
try adding .setAutoCancel(true); in your AlarmManagerBroadcastReceiver class after this line
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context,
ChannelIdApp.CHANNEL_ID);
builder.setAutoCancel(true)
.setTicker("Alarm")
.setCustomContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setSmallIcon(R.drawable.ic_stat_notify_clock)
// <<here>> ;

Categories