Notification doesn't appear to android 8+ - java

With this code, I want to click in a button and appear a notification. The problem is when in click in my button doesn't appear when I test in emulator api 26+. In api below 26 appear normally without problems.
btNotify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notification();
}
});
public void notification() {
RemoteViews remoteViews = new
RemoteViews(getApplicationContext().getPackageName(),R.layout.notification_collapsed);
remoteViews.setTextViewText(R.id.title, "Atividade");
remoteViews.setTextViewText(R.id.act, activity);
remoteViews.setChronometer(R.id.timer, chronometer.getBase(), chronometer.getFormat(), !running);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "notification")
.setSmallIcon(R.drawable.ic_baseline_access_time_24)
.setContent(remoteViews)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notifManager != null;
notifManager.notify(1, builder.build());
}

Related

How to disable all the incoming push notification when your in the desired activity?

As the title implies, how can I prevent my app from getting notifications when I'm in the desired activity? I'm developing a chat application wherein users can get notifications when a new message has been posted, how can I prevent the notification when the user is in the chat activity?
here's FirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
super.onMessageReceived(message);
int requestID = (int) System.currentTimeMillis();
String title = message.getNotification().getTitle();
String body = message.getNotification().getBody();
String click_action=message.getNotification().getClickAction();
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),"Notification");
builder.setContentTitle(title);
builder.setContentText(body);
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
builder.setLights(getResources().getColor(R.color.chitchat), 3000, 3000);
builder.setSmallIcon(R.drawable.logowhite);
Intent intent = null;
//message.getData().get("type");
if (Objects.requireNonNull(message.getData().get("type")).equalsIgnoreCase("privatechat"))
{
intent = new Intent(click_action);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("GCKey", message.getData().get("GCKey"));
intent.putExtra("GCNameKey", message.getData().get("GCNameKey"));
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE );
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("Notification", "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(69, builder.build());
}
}
It should not be hard. You can just create a class where you have a static variable where you just set the activity and before notifying, check whether you want to show notification or not. This would go this way:
Make a new class with a static variable
public class NotificationHelper {
public static boolean shouldShowNotification = true;
}
In the activity you don't want the notification to show in add this code:
#Override
public void onResume(){
super.onResume();
NotificationHelper.shouldShowNotification = false;
}
#Override
public void onPause(){
super.onPause();
NotificationHelper.shouldShowNotification = true;
}
In the MyFirebaseMessagingService class, add a condition to before executing the code.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
super.onMessageReceived(message);
if(NotificationHelper.shouldShowNotification){
// your code goes here...
}
}
}

stop service in BroadcastReceiver

I got some problems in android studio. I would like to use stopService() to close my service, but its not working.
Here is my project going
click button in MainActivity.java and Start Service Service_Record.class
cardView_Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(this,Service_Record.class));
}
});
2-1. create notification in Service_Record.class(Service) onCreate()
//step 4 create action
intent_sleep=new Intent(Service_Record.this,Service_RecordData.class);
intent_sleep.setAction("stop");
PendingIntent pendingIntent_sleep =
PendingIntent.getBroadcast(Service_Record.this,1,intent_sleep,PendingIntent.FLAG_UPDATE_CURRENT);
//step1 create channel
createNotificationChannel();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//step2 setting context
builder = new NotificationCompat.Builder(this, "channel_Sleep")
.setSmallIcon(R.drawable.rec)
.setContentTitle("Recording")
.setContentText("It is recording.Press stop button when you awake.")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("It is recording.Press stop button when you awake."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.stop,"Stop",pendingIntent_sleep)
.setOngoing(true);
//step3 create
notificationManager.notify(0,builder.build());
2-2. upload value to firebase for every 10 secs in Service_Record.class(Service) onCreate()
if(timer!=null){
timer.purge();
timer.cancel();
}
timer=new Timer();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
insertDot();
}
};
timer.schedule(timerTask,0,10000);
close service by clicking notification's button in Service_RecordData.java (receiver)
public class Service_RecordData extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (action != null) {
if (action.equals("stop")) {
mNotificationManager.cancel(0);
//Something wrong
context.stopService(new Intent(context,Service_Record.class));
}
}
}
}
Mainfest.xml
<receiver android:name=".Service_RecordData" />
<service android:name=".Service_Record"/>
I found out the problem since my firebase kept uploading value after I closed the notification and APP. Thanks for helping.
OK, I found how to fix it. But I still can't figure out the problem. If anyone know what happened, I'll give you the mark. THX.
context.stopService(new Intent(context,Service_Record.class));
into
Intent intent_service = new Intent(context,Service_Record.class);
context.stopService(intent_service);

Android 8.1 notifications showing but not making any sounds

I have a service which runs in foreground with, among other things, a stopwatch. When the service starts the notification appears, and when it ends I update it with sound and some text that indicates that it's finished. The problem is that this works well until api 25, but for 26 and 27 it updates the notification alright, but makes no sound. Here's the relevant code:
The creation of the notification inside the service:
mBuilder = new NotificationCompat.Builder(context, "Main")
.setSmallIcon(R.drawable.ic_notification_temp)
.setContentTitle(step.getDescription())
.setContentText(getString(R.string.notification_text))
.setVisibility(VISIBILITY_PUBLIC)
.setOngoing(true);
.setDeleteIntent(deletePendingIntent);
.setContentIntent(contentPendingIntent);
.addAction(R.drawable.ic_stop_red_24dp, getString(R.string.cancel),finnishPendingIntent);
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
The update to the notification builder when the "work" is finished:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setVibrate(new long[]{0, 300, 0, 400, 0, 500});
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mBuilder.setContentText(getString(R.string.notification_finished_text));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setChannelId("Sound");
mBuilder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
mNotificationManager.notify(mId, mBuilder.build());
The 2 channels created just for api 26 or up on app start:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the normal NotificationChannel
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel("Main", name, importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
// Create theNotificationChannel with sound
importance = NotificationManager.IMPORTANCE_HIGH;
name = getString(R.string.notification_channel_sound);
NotificationChannel sound = new NotificationChannel("Sound", name, importance);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
notificationManager.createNotificationChannel(sound);
}
And that's where I'm at now. I've tried to not use setsound() as I've read that the notification should just play the default sound with the appropriate importance (and of course I've even uninstalled the app between tries to correctly update the channel settings) but nothing seems to work for api 26 and I just don't know what I'm doing wrong.
I had the exact same problems with most of my emulator AVDs. The following fixed it for me:
start the affected AVD
long press the AVD's power button
restart the AVD
Afterwards it should work again.
Tried to reproduce your issue and finished with created MVP, maybe this will help you to find the problem:
Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View btn = findViewById(R.id.clickMe);
btn.setTag(NotifService.CHANNEL_ID_MAIN);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String channelId = (String) v.getTag();
Intent intent = new Intent(v.getContext(), NotifService.class);
intent.putExtra(NotifService.TAG, channelId);
if (channelId.equals(NotifService.CHANNEL_ID_MAIN)) {
v.setTag(NotifService.CHANNEL_ID_SOUND);
} else {
v.setTag(NotifService.CHANNEL_ID_MAIN);
}
v.getContext().startService(intent);
}
});
}
}
Service:
public class NotifService extends IntentService {
public static final String TAG = "NotificationService";
public static final String CHANNEL_ID_MAIN = "Main";
public static final String CHANNEL_ID_SOUND = "Sound";
public static final int NOTIFICATION_ID = 123;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public NotifService() {
super(TAG);//Used to name the worker thread, important only for debugging.
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_MAIN, "Channel Main", NotificationManager.IMPORTANCE_LOW);
NotificationChannel sound = new NotificationChannel(CHANNEL_ID_SOUND, "Channel Sound", NotificationManager.IMPORTANCE_HIGH);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
notificationManager.createNotificationChannel(sound);
}
}
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
String channelId = intent.getStringExtra(TAG);
showNotification(channelId);
}
private void showNotification(String channelId) {
boolean inProgress = channelId.equals(CHANNEL_ID_MAIN);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Work")
.setContentText(inProgress ? "InProgress" : "Finished")
.setOngoing(inProgress)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(!inProgress);
if (!inProgress) {
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
}
This works good on my device 8.1 and Emulator 8.1 (without sound on first click for first notification and with vibration + sound on second click for work complete notification).

Non activity class notification not working

I'm trying to make a notification appear in the notification manager from a non activity class, but I can't make it happen
public void showNotification(Context context) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//.setSmallIcon(R.drawable.notif1)
.setContentTitle("Car crash occure!")
.setContentText("Tap to view location.");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MapsActivity.class), 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
Use Intent Service instead of Activity
public static class NotificationActionService extends IntentService {
public NotificationActionService() {
super(NotificationActionService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_1.equals(action)) {
Log.d("ACTION_NOTIFICATION", "Notification Clicked");
}
// TODO: handle action 1.
// If you want to cancel the notification: NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID);
}
}

Error with Notification.Builder in notify

Hello I am new to Android, and I 'm trying to create notifications Notification.Builder and I failed . When launching the notification I get error
nm.notify(IDNOTIFICACIONUNO,notif); // Error in notif
I have downloaded the API 'S 16 17 18 19 23,
and this is all code :
public class MainActivity extends AppCompatActivity {
NotificationManager nm;
private static final int IDNOTIFICACIONUNO = 1;
Notification notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLanzar = (Button) findViewById(R.id.boton_notificacion);
btnLanzar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),segundaVentana.class);
PendingIntent intencionPendiente = PendingIntent.getActivity(getApplicationContext(),0,i,0);
Notification.Builder notif = new Notification.Builder(getApplicationContext());
notif.setSmallIcon(R.drawable.tree);
notif.setTicker("App Nature ¡TIP!");
notif.setWhen(System.currentTimeMillis());
notif.setContentTitle("App Nature ¡TIP!");
notif.setContentText("Cierra la llave, cuando te estes cepillando");
notif.setContentInfo("TIP");
notif.setContentIntent(intencionPendiente);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(IDNOTIFICACIONUNO,notif);
}
});
}
I also libraries . Thank you for your help
there is a ` characheter after notif.setSmallIcon(R.drawable.tree);
remove that charachter and code will run.
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Connect to the button
Button iconBtn = (Button) findViewById(R.id.btn_icon);
//Set the button on click listener
iconBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
Notification notification = builder.setContentIntent(contentIntent).setTicker("This is a notification marquee")
.setSmallIcon(R.drawable.ic_launcher).setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle("Message Title")
.setContentText("Message Content").build();
//Show the notification
nm.notify(1, notification);
}
});

Categories

Resources