I replaced this (it allows me to show the notification only when the app was open):
private void addNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel =
new NotificationChannel("MyNotifications", "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifications")
.setContentTitle("Chiamata in arrivo da "+ receiverUserName)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentText("Apri FtoF per partecipare alla videochiamata");
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
with this (it allowed me to show the notification even when the app was closed:
public class PushNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//at this point the context has the permission to create remote views
addNotification(context);
setResultCode(Activity.RESULT_OK);
}
private void addNotification(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel =
new NotificationChannel("MyNotifications", "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "MyNotifications")
.setContentTitle("Chiamata in arrivo")
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentText("Apri FtoF per partecipare alla videochiamata");
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.notify(999, builder.build());
}
}
But now on line 283 this error appears: Cannot resolve method 'addNotification ()'
Does anyone know why?
Complete Code: https://codeshare.io/5D8EgE
lines (111-136) (283)
Thank you
Related
I get this code from google android developer website, but I'm not sure why I'm getting this error. First I did this in my MainActivity and it works fine, and then I created another at AlarmReceiver.java but error occurred.
error: cannot find symbol method getSystemService(Class)
public class AlarmReceiver extends BroadcastReceiver{
private final String CHANNEL_ID = "Notification";
#Override
public void onReceive(Context context, Intent intent) {
createNotificationChannel();
Intent notificationIntent = new Intent(context, MapsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
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 = "NOTIFICATION";
String description = "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 behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
I'm developing a stopwatch that can show three notifications. When i update the notifications (every second), all of them are heading up in the notification bar, switching between them.
Is there any way to prevent them from moving to the top every time they are updated?
With the following code I create notifications from different services, each one with unique CHANNEL_ID and NOTIFY_ID.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,getResources().getText(R.string.stopwatch_channel),
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
private Notification sendNotification(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getResources().getText(R.string.stopwatch)+" ยท "+String.format("%02d:%02d:%02d",hour,min,secs))
.setSmallIcon(R.drawable.ic_stopwatch_24dp)
.setContentIntent(pendingIntent)
.setShowWhen(false)
.build();
return notification;
}
private void updateNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFY_ID, sendNotification());
}
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>> ;
I have given my couple of days to solve this issue. My app is getting crash whose android version is 8.1. It is working perfectly fine in Android Version 8.0.
I followed the link mentioned below for the solution and tried many solutions given in this link but my application is not opening.
startForeground fail after upgrade to Android 8.1
I check the Android version in FirebaseMessageService class and create the channel for Oreo version but below given error is showing everytime
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Here below is my code. Please help me to rectify this problem
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
private NotificationManager notifManager;
Context mContext;
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
sendNotification();
}
public void sendNotification()
{
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logipace")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel(channelId, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Below is the code which I used in the onCreate() method of my Activity class.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
// Create channel to show notifications.
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.default_notification_channel_name);
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_LOW));
}
Help me to resolve this issue.
Put your logic inside onMessageReceived: Check Firebase quickstart sample.
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
final String msg = object.getString("msg");
sendNotification(msg);
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Notification is showing on android nougat 7.0 and less but not on Orea 8.0
What should i do?
......................................................................................................................................................
Here is my code:
public class MainActivity extends AppCompatActivity {
Button button;
private final String ChannelId = "Notification";
private final Integer NotificationId = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
}
public void sendNotification (View view) {
Toast.makeText(this, "Notification", Toast.LENGTH_SHORT).show();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, ChannelId);
Intent i = new Intent(MainActivity.this, Main2Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder.setWhen(20000);
mBuilder.setTicker("Ticker");
mBuilder.setContentInfo("Info");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setContentTitle("New notification title");
mBuilder.setContentText("Notification text");
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(2, mBuilder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = "Notification";
CharSequence channelName = "Some Channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
I think you should use notification channel to create the notification
check if Build.VERSION.SDK_INT >= Build.VERSION_CODES.O and then use the channel
here is an example I found on the documentation
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 behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
then you use builder to build the notification and then you continue as normal
https://developer.android.com/training/notify-user/channels
This article should be of a good guide to you, according to the new way of implementing Notifications on Android, you need to do that through a Notification Channel
I faced some difficulties implementing this, even though there are so many examples, but here is how it worked for me:
public class RingtonePlayingService extends Service {
NotificationCompat.Builder notificationBuilder;
NotificationManager notificationManager;
NotificationChannel notificationChannel;
String channelId;
CharSequence channelName;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
initNotification();
showNotification();
return START_STICKY;
}
private void initNotification() {
setNotificationChannel();
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
// The methods called for building are following my own needs, change them according to yours
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.alarm)
.setContentTitle("Alarm On!")
.setContentText("Click the notification to dismiss")
.setPriority(NotificationCompat.PRIORITY_HIGH)
// You can add your intents or actions here
.setAutoCancel(true);
}
private void showNotification() {
// You can use a unique alarmRequestCode or just use 1 for testing purposes
notificationManager.notify(alarmRequestCode, notificationBuilder.build());
}
private void setNotificationChannel() {
channelId = "alarm_channel_id";
channelName = "alarm_notification_channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Please note that I removed the if statement since I upgraded my whole gradle to work only with the new versions.
Also I removed all the snippets of code which you might not need so I can make it easier for you to follow, so if the code doesn't really make sense to you remember that you will need to implement this within your own purpose and code!
I hope this will be of a good help :)