I'm working on an app where using two switch buttons the user can turn on/off notifications and notification sound. I created the notifications that pop up on the status bar and I want to play a default sound when they appear.I wrote the following code but it doesn't seem to work. Any ideas about how can I make the notification sound play ?
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import java.util.Set;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
import static com.example.myevents.R.drawable.notification;
public class Settings extends AppCompatActivity {
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
NotificationManager manager;
Notification myNotication;
boolean enableSound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleswitch1.setChecked(false);
simpleswitch2.setChecked(false);
simpleswitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#TargetApi(Build.VERSION_CODES.P)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
int notifyID = 1;
String CHANNEL_SOUND_ID = "channel SOUND";// The id of the channel.
CharSequence NAME_SOUND = "channel 1";// The user-visible name of the channel.
String CHANNEL_SILENT_ID = "channel SILENT";// The id of the channel.
CharSequence NAME_SILENT = "channel 2";// The user-visible name of the channel.
int importance_sound = NotificationManager.IMPORTANCE_HIGH;
int importance_silent = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel_sound = new NotificationChannel(CHANNEL_SOUND_ID, NAME_SOUND, importance_sound);
NotificationChannel mChannel_silent = new NotificationChannel(CHANNEL_SILENT_ID, NAME_SILENT, importance_silent);
// Crete both notification channels
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel_sound);
mNotificationManager.createNotificationChannel(mChannel_silent);
Intent intent = new Intent(Settings.this, Visitor.class);
intent.putExtra("yourpackage.notifyId", notifyID);
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Select the correct notification channel
String selectedChannelId;
if (enableSound) {
selectedChannelId = CHANNEL_SOUND_ID;
} else {
selectedChannelId = CHANNEL_SILENT_ID;
}
// Create a notification and set the notification channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Settings.this, selectedChannelId);
notificationBuilder.setSmallIcon(R.drawable.cheers);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Notification");
notificationBuilder.setContentIntent(pIntent);
notificationBuilder.setChannelId(selectedChannelId);
Notification notification = notificationBuilder.build();
// Issue the notification.
mNotificationManager.notify(notifyID, notification);
}}});
simpleswitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enableSound = isChecked;
}
});
}}
You should define a flag to toggle the sound on/off. This could be a boolean value controlled by the second switch. Then check the status of that flag when creating the notification and decide to set or not the sound.
And maybe split the Notification from the NotificationBuilder to control the sound.
1- Create the flag being a Class attribute
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
NotificationManager manager;
Notification myNotication;
// Sound disabled by default
boolean enableSound = false;
2- Control the flag with the second switch
simpleswitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enableSound = isChecked;
}
});
3- Use the NotificationBuilder to control the sound. Replace this piece of code from first switch
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Settings.this, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.notification);
notificationBuilder.setContentTitle("NOTIFICATION TITLE");
notificationBuilder.setContentText("You have a new notification");
notificationBuilder.setChannelId(CHANNEL_ID);
if (enableSound){
notificationBuilder.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI);
notificationBuilder.setVibrate(new long[]{1000,100});
}
Notification notification = notificationBuilder.build();
I hope it helps!
UPDATE
I think I know why it's not playing a sound. I've just created a new Android Studio Project and copy-paste your code and the notifications is fired, the sound plays and I can not turn the sound off (just the oppostite). And I'm guessing your problem is related to the notification channel. Then I modify my App and it worked!
First, let me correct myself. The PRIORITY has been deprecated since api level 26 (which you are using according to #TargetApi(Build.VERSION_CODES.O)) and what you should use instead is the IMPORTANCE in the NotificationChannel. The problem with a notification channel is that you can not edit it once created (unless you uninstall your app). So if at first you where using a low importance channel and then change it to a high one it won't take any effect.
So what you really need is two notifications channel: one with sound and one silent, and then select the appropiate channel with the help of the previously created flag.
So now, the code for the first switch would be: Notice I re-arrange it so I first create the NotificationChannel (for better readability)
if (isChecked){
int notifyID = 1;
String CHANNEL_SOUND_ID = "channel SOUND";// The id of the channel.
CharSequence NAME_SOUND = "channel 1";// The user-visible name of the channel.
String CHANNEL_SILENT_ID = "channel SILENT";// The id of the channel.
CharSequence NAME_SILENT = "channel 2";// The user-visible name of the channel.
int importance_sound = NotificationManager.IMPORTANCE_HIGH;
int importance_silent = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel_sound = new NotificationChannel(CHANNEL_SOUND_ID, NAME_SOUND, importance_sound);
NotificationChannel mChannel_silent = new NotificationChannel(CHANNEL_SILENT_ID, NAME_SILENT, importance_silent);
// Crete both notification channels
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel_sound);
mNotificationManager.createNotificationChannel(mChannel_silent);
Intent intent = new Intent(Settings.this, Visitor.class);
intent.putExtra("yourpackage.notifyId", notifyID);
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Select the correct notification channel
String selectedChannelId;
if (enableSound){
selectedChannelId = CHANNEL_SOUND_ID;
}else{
selectedChannelId = CHANNEL_SILENT_ID;
}
// Create a notification and set the notification channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Settings.this, selectedChannelId);
notificationBuilder.setSmallIcon(R.drawable.notification);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Notification Text");
notificationBuilder.setContentIntent(pIntent);
notificationBuilder.setChannelId(selectedChannelId);
Notification notification = notificationBuilder.build();
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
}
Related
I need a button in my Notification, however everything i find online is not working. I need it to cancel playing an alarm that will go off at a designated time. Can anyone link me some articles to read or tell me what code i should use in order to get this to work.
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import com.example.oceansscheduler.MainActivity;
import com.example.oceansscheduler.R;
public class AlarmReceiver extends BroadcastReceiver {
public void showNotification(Context context, String title, String message, Intent intent, int reqCode) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, reqCode, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_name";// The id of the channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_alarm_24)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle())
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentText(message)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel Name";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(reqCode, notificationBuilder.build()); // 0 is the request code, it should be unique id
Log.d("showNotification", "showNotification: " + reqCode);
}
#Override
public void onReceive(Context context, Intent intent) {
SQLiteDatabase db = context.openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);
Log.d("Count", String.valueOf(data.getCount()));
if (data.getCount() > 0) {
data.moveToFirst();
String NameOfNotif = (data.getString(0));
Toast.makeText(context, NameOfNotif, Toast.LENGTH_LONG).show();
int reqCode = 1;
Intent intentNotif = new Intent(context, MainActivity.class);
showNotification(context, NameOfNotif, "Your Reminder is going off!", intentNotif, reqCode);
}
}
};
To add a button in Your notification, You need to use addAction function.
It requires an Action object which needs:
an icon (oddly),
a title,
a PendingIntent
The PendingItent can encapuslate an Intent that can be a Service that will be delegated to cancel playing the alarm or a Receiver that will do it.
Let's stick with a receiver. We can create one - CancelAlarmReceiver:
public class CancelAlarmReceiver extends BroadcastReceiver {
public static String ACTION_CANCEL = "actionCancelAlarm";
public CancelAlarmReceiver() {}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_CANCEL)) {
// Here You will cancel the alarm.
}
}
}
Remember to register it in the Manifest:
<receiver
android:name=".CancelAlarmReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.your.app.CancelAlarmReceiver.ACTION_CANCEL" />
</intent-filter>
</receiver>
Later on, when creating a notification with a builder, You will have to provide an action leading to our Receiver:
Intent cancelIntent = new Intent(this, CancelAlarmReceiver.class);
cancelIntent.setAction(ACTION_CANCEL);
PendingIntent cancelPendingIntent =
PendingIntent.getBroadcast(this, NOTIFICATION_ID,
cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(
new Notification.Action(
R.drawable.ic_alarm_cancel,
getString(R.string.cancel_alarm),
cancelPendingIntent
)
);
This should make sure that a button will appear by Your notification and it will trigger the receiver and disable the alarm (or whatever You will make it to do).
I'm trying to fire a notification when the battery level is less the %10.
here is my notification class located at MainActivity.java
public void notify(View view) {
String title = "Warning! low battery";
String text = "Please plug your mobile device to a charger";
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_qs_battery_saver)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(notificationID++, notification);
}
I'm trying to fire it from the BatteryReceiver class:
package com.michal.ex2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;
import android.view.View;
public class BatteryReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level * 100) / scale;
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean isPlugged;
isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
if ((percent == 10) && !isPlugged) {
Log.d("mylog", "low battery");
//notify();
synchronized(mActivity){
mActivity.notify();
}
}
}
}
First i tried calling calling notify from MainActivity, but the app crash with the error:
java.lang.IllegalMonitorStateException: object not locked by thread before notify()
I've searched for a solution and found that I need to lock the notify, so I tried calling it with synchronized():
synchronized(mActivity){
mActivity.notify();
but nothing happened. The battery receiver works alright(I'm getting the right log message) but notify() is not been called.
Maybe the function you'are calling is not the MainActivity.notify(View view) but the Object.notify(). Therefore nothing happens. Give an appropriate function argument.
mActivity.notify(null);
I'm using the following code to generate a mediaPlayer notification:
package com.app1.notificationtemplate;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
public class NotificationGenerator {
public static final int NOTIFICATION_ID_OPEN_ACTIVITY = 9;
public static final String NOTIFY_PREVIOUS = "com.a.b.previous";
public static final String NOTIFY_DELETE = "com.a.b.delete";
public static final String NOTIFY_PAUSE = "com.a.b.pause";
public static final String NOTIFY_PLAY = "com.a.b.play";
public static final String NOTIFY_NEXT = "com.a.b.next";
public static void openActivityNotificaton(Context context) {
NotificationCompat.Builder nc = new NotificationCompat.Builder(context,
MainActivity.channelID);
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(context, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.mipmap.ic_launcher);
nc.setAutoCancel(true);
nc.setContentTitle("Notification Demo");
nc.setContentText("Click please");
nm.notify(NOTIFICATION_ID_OPEN_ACTIVITY, nc.build());
}
public static void customBigNotification(Context context){
final RemoteViews expandedView = new RemoteViews(context.getPackageName(), R.layout.big_notification);
NotificationCompat.Builder nc = new NotificationCompat.Builder(context, MainActivity.channelID);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(context, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.drawable.play);
nc.setAutoCancel(true);
nc.setCustomBigContentView(expandedView);
nc.setContentTitle("MusicPlayer");
nc.setPriority(NotificationCompat.PRIORITY_MAX);
nc.setContentText("Control AUdio");
//expandedView.setTextViewText(R.id.text_song_name,"Adele");
setListeners(expandedView, context);
Notification notification = nc.build();
notification.flags = NotificationCompat.FLAG_ONGOING_EVENT|NotificationCompat.FLAG_FOREGROUND_SERVICE
| NotificationCompat.FLAG_NO_CLEAR|NotificationCompat.FLAG_BUBBLE ;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
nm.notify("newNotif", 1, nc.build());
}
public static void setListeners(RemoteViews view, Context context){
Intent previous = new Intent(NOTIFY_PREVIOUS);
Intent delete = new Intent(NOTIFY_DELETE);
Intent pause = new Intent(NOTIFY_PAUSE);
Intent next = new Intent(NOTIFY_NEXT);
Intent play = new Intent(NOTIFY_PLAY);
PendingIntent pPrevious = PendingIntent.getBroadcast(context, 0,
previous, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnPrevious, pPrevious);
PendingIntent pDelete = PendingIntent.getBroadcast(context, 0,
delete, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnDelete, pDelete);
PendingIntent pPause = PendingIntent.getBroadcast(context, 0,
pause, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnPause, pPause);
PendingIntent pPlay = PendingIntent.getBroadcast(context, 0,
play, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnPlay, pPlay);
PendingIntent pNext = PendingIntent.getBroadcast(context, 0,
next, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnNext, pNext);
}
}
I have custom notification views (RemoteViews) setup for the notification as well.
but, when I click play, I'm not sure how to update the play view to a pause view. Currently, I'm just setting the visibility of the play button to gone. But, is turning on and off the visibility turnwise the only option? And how do I do that anyways(the tutorial I've followed doesn't really show this). But, I think it'd be better if we could replace the image in the button which would avoid possible blinking or flickering. I've also gotta update the Remote view's artist and song Title name, but have no idea to do so. Please tell me how to update views in the RemoteView according to user interaction
Also, to communicate from the notification to the Service is using Broadcasts the only option? What other options do I have?
You need to create a new notification with the updated data and use NotificationManager to update it. No need to start service again. You have a running foreground service, all you have to do is update your UI via notify.
So in your Broadcast Receiver call your openActivityNotificaton() function with updated data, according to what view was clicked inside the notification. You can have one Receiver with a unique action for each view click, and update notification accordingly. I tested and it does not cause a blink, the notification is updated smoothly.
The code for your Receiver would be something like this:
const val NOTIFICATION_TITLE_INTENT_ACTION = "notification_title_intent_action"
const val NOTIFICATION_ARROW_INTENT_ACTION = "notification_arrow_intent_action"
class NotificationInteractionReceiver : BroadcastReceiver() {
private lateinit var notificationsFactory: NotificationFactory
override fun onReceive(context: Context, intent: Intent) {
notificationsFactory = NotificationFactory(context)
// Update title according to what button was clicked
val newTitle = when (intent.action) {
NOTIFICATION_TITLE_INTENT_ACTION -> "title clicked"
else -> "arrow clicked"
}
// Pass new title to class responsible for showing notification
notificationsFactory.showNotification(context, s)
}
companion object {
fun getIntent(context: Context, action: String): Intent {
val intent = Intent(context, NotificationInteractionReceiver::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
intent.action = action
return intent
}
}
}
This question already has an answer here:
How to play sound when a notification pops up?
(1 answer)
Closed 2 years ago.
I'm developing an app that sends notifications to the user with a message and a sound. There are two switches, 1 to turn on and off the notifications and the second to turn on and off the notification sound. I wrote the code for the notification sound but it doesn't seem to work.
Do you have any idea about how to make the notification sound to play when a notification pops up?
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import java.util.Set;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
import static com.example.myevents.R.drawable.notification;
public class Settings extends AppCompatActivity {
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
NotificationManager manager;
Notification myNotication;
boolean enableSound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleswitch1.setChecked(false);
simpleswitch2.setChecked(false);
simpleswitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#TargetApi(Build.VERSION_CODES.O)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = "channel 1";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
Intent intent = new Intent(Settings.this, Visitor.class);
intent.putExtra("yourpackage.notifyId", notifyID);
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create a notification and set the notification channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Settings.this, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.notification);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("New notification");
notificationBuilder.setContentIntent(pIntent);
notificationBuilder.setChannelId(CHANNEL_ID).build();
if (enableSound){
notificationBuilder.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI);
notificationBuilder.setVibrate(new long[]{1000,100});
}
Notification notification = notificationBuilder.build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
}
simpleswitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enableSound = isChecked;
}
});
}});}}
UPDATED
Once you have setdefault on a notificationbuilder, it will ignore subsequent calls like setsound and setvibrate.
You have to set sound and vibration in setdefault method always.
if (shouldSound && !shouldVibrate) {
builder.setDefaults(Notification.DEFAULT_SOUND)
.setVibrate(new long[]{0L});
}
if (shouldVibrate && !shouldSound) {
builder.setDefaults(Notification.DEFAULT_VIBRATE)
.setSound(null);
}
if (shouldSound && shouldVibrate) {
builder.setDefaults(Notification.DEFAULT_ALL);
}
For a simple working example of Notifications on all versions, you can consult the following repo https://github.com/usman14/Notification
I am trying to build a simple app that sends notifications to the device but only on a specific day/time. I have been able to get the notification part to work but cant seem to get the day & time problem solved. Any ideas?
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class NotificationsActivity extends Activity {
int notificationID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
displayNotification();
}
protected void displayNotification()
{
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.ic_launcher,
"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
notif.vibrate = new long[] { 100, 250, 100, 500};
nm.notify(notificationID, notif);
}
}
You need to use an AlarmManager to schedule these events. Then, from the callbacks, you show the notifications.
See for example Creating a Notification at a particular time through Alarm Manager
Be careful, as AlarManager will be cleared when the device reboots (you may need to re-register then on boot completed if necessary).
See this link Notification in Android Using AlarmManager, BoradCastReceiver & Services
It may be help you.