Reputation: 5202
I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.
I have established code. The notification should be working, but for some reason it is not working. The Notification
isn't showing at all. I don't know what am I missing.
Code of those files:
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "[email protected]")
.setContentText("Subject")
.setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(longText))
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected
notificationManager.notify(0, n);
Upvotes: 151
Views: 157892
Reputation: 965
If you are using a service don't forget to add the service in manifest under application tag
<service android:name=".service.MyForegroundService"/>
Also, make sure necessary permissions are added and granted
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
Upvotes: 0
Reputation: 1
Code for android alarm clock with notification
mainactivity.kt
import android.Manifest
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TimePicker
import android.widget.Toast
import android.widget.ToggleButton
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import java.util.Calendar
import java.util.Date
class MainActivity : AppCompatActivity() {
private lateinit var timePicker: TimePicker
private lateinit var toggleButton: ToggleButton
private var hr = 0
private var min = 0
private lateinit var pendingIntent: PendingIntent
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermission()
}
timePicker = findViewById(R.id.timePicker)
toggleButton = findViewById(R.id.toggleButton)
timePicker.setOnTimeChangedListener { view, hourOfDay, minute ->
hr = hourOfDay
min = minute
}
toggleButton.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked)
{
Toast.makeText(this, "ALARM SET, For $hr:$min!", Toast.LENGTH_SHORT).show()
setTimer()
notification()
}
else
{
Toast.makeText(this, "ALARM CLEARED, For $hr:$min!", Toast.LENGTH_SHORT).show()
}
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun requestPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 444)
return
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun notification() {
val name = "ALARM!!!"
val desc = "WAKE UP!!!!!!!!!"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("Notify", name, importance)
channel.description = desc
val notificationManager = getSystemService(NotificationManager::class.java) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
private fun setTimer() {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val date = Date()
var timeNow = Calendar.getInstance()
var timeAlarm = Calendar.getInstance()
timeNow.time = date
timeAlarm.time = date
timeAlarm.set(Calendar.HOUR_OF_DAY, hr)
timeAlarm.set(Calendar.MINUTE, min)
timeAlarm.set(Calendar.SECOND, 0)
if (timeAlarm.before(timeNow))
timeAlarm.add(Calendar.DATE, 1)
val intent = Intent(this, MyBroadcastReceiver::class.java)
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager.set(AlarmManager.RTC_WAKEUP, timeAlarm.timeInMillis, pendingIntent)
}
}
xml code
<TimePicker
android:id="@+id/timePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.26" />
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="@string/set_alarm"
android:textOn="CLEAR ALARM"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/timePicker" />
Upvotes: 0
Reputation: 421
In addition to the suggestions in the previous answers, when using API 33+ you'll need to declare this dangerous permission in your manifest:
and also request it from the user at runtime.
Upvotes: 1
Reputation: 3057
Make sure your notificationId is unique. I couldn't figure out why my test pushes weren't showing up, but it's because the notification ids were generated based on the push content, and since I was pushing the same notification over and over again, the notification id remained the same.
Upvotes: 1
Reputation: 351
I encountered a similar problem to yours and while searching for a solution I found these answers but they weren't as direct as I hoped they would be but it gives an Idea; Your notifications may not be showing because for versions >=8 notifications are done relatively differently there is a NotificationChannel
which aids in managing notifications this helped me. Happy coding.
void Note(){
//Creating a notification channel
NotificationChannel channel=new NotificationChannel("channel1",
"hello",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
//Creating the notification object
NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"channel1");
//notification.setAutoCancel(true);
notification.setContentTitle("Hi this is a notification");
notification.setContentText("Hello you");
notification.setSmallIcon(R.drawable.ic_launcher_foreground);
//make the notification manager to issue a notification on the notification's channel
manager.notify(121,notification.build());
}
Upvotes: 1
Reputation: 1
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)
var notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(sameId, notification)
Upvotes: -2
Reputation: 5202
The code won't work without an icon. So, add the setSmallIcon
call to the builder chain like this for it to work:
.setSmallIcon(R.drawable.icon)
Android 8 introduced a new requirement of setting the channelId
property by using a NotificationChannel
.
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
Upvotes: 490
Reputation: 4258
If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
Upvotes: 0
Reputation: 3999
Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.
Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel()
and then NotificationManager.notify()
might then sometimes cause this behavior.
If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify()
with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.
Upvotes: 0
Reputation: 781
You also need to change the build.gradle file, and add the used Android SDK version into it:
implementation 'com.android.support:appcompat-v7:28.0.0'
This worked like a charm in my case.
Upvotes: 2
Reputation: 4102
For me it was an issue with deviceToken
. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.
For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.
// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken = instanceIdResult.getToken();
// Insert device token into Firebase database
fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
});
Upvotes: 1
Reputation: 91
I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).
After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.
Upvotes: 1
Reputation: 1015
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
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 = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Upvotes: 14
Reputation: 950
This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.
I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.
Upvotes: 23
Reputation: 3388
Actually the answer by ƒernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification
simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification
will not show without one.
addAction
is only available since 4.1. Prior to that you would use the PendingIntent
to launch an Activity
. You seem to specify a PendingIntent
, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
Upvotes: 59
Reputation: 3714
I think that you forget the
addAction(int icon, CharSequence title, PendingIntent intent)
Look here: Add Action
Upvotes: 1
Reputation: 478
You were missing the small icon. I did the same mistake and the above step resolved it.
As per the official documentation: A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.
See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Upvotes: 37