Kratos
Kratos

Reputation: 937

Android notification not working as expected

I want to create notification WITH SOUND & VIBRATION that will appear every 3 days. I cannot make it happen

Tried almost every solution I found on the internet. You will see it from my code. With my code, the sound is not working, vibration is not working, notification is showing more times in a row even when cancelled, it is not showing on the screen when locked even though I set priority to high. super weird

this is function that sets notification in MainActivity:

public void setNotification() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());

        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 45);

        Intent myIntent = new Intent(this, NotifyService.class);
        int ALARM1_ID = 10000;
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, ALARM1_ID, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        assert alarmManager != null;
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 3, pendingIntent);
    }

this is BroadcastReceiver that triggers the notification:

public class NotifyService extends BroadcastReceiver {

    @SuppressLint("ResourceAsColor")
    @Override
    public void onReceive(Context context, Intent intent) {

            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("my_channel_01ee",
                        "Channel human readable titlee",
                        NotificationManager.IMPORTANCE_HIGH);
                channel.enableVibration(true);
                channel.setVibrationPattern(new long[]{
                        0
                });

                channel.enableLights(true);
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

                channel.setLightColor(Color.GRAY);
                channel.enableLights(true);
                channel.setDescription("descrioptiom");
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build();
                channel.setSound(alarmSound, audioAttributes);
                notificationManager.createNotificationChannel(channel);

            }

            Intent notificationIntent = new Intent(context, FoodInspectorActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder notification = new NotificationCompat.Builder(context, "my_channel_01ee");

            int color = 0xfffffff;
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                notification.setSmallIcon(R.drawable.magnifier_final);
                notification.setColor(color);
            } else {
                notification.setSmallIcon(R.drawable.magnifier_final);
            }

            notification.setContentTitle("FoodScan")
                    .setContentText("Scan some new products? Just click!")
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher_icon))
                    .setSound(alarmSound)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setDefaults(Notification.DEFAULT_LIGHTS )
                    .setVibrate(new long[]{0, 500, 1000});

            assert notificationManager != null;
            notificationManager.notify(5, notification.build());

        }
}

With this code, the sound is not working, vibration is not working, notification is showing more times in a row even when cancelled, it is not showing on the screen when locked even though I set priority to high. super weird

Upvotes: 1

Views: 247

Answers (1)

Jimale Abdi
Jimale Abdi

Reputation: 2854

Step 1: Create Method in your MainActivity and use AlarmManager to set alarm at specified time, and call the method in OnCreate

public void my(){

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,21);
calendar.set(Calendar.MINUTE,47);
if (calendar.getTime().compareTo(new Date()) < 0) 
calendar.add(Calendar.DAY_OF_MONTH, 1);
Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
if (alarmManager != null) {
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}


 }

I'm setting my alarm every day at 09:47 PM

Step 2: Create BroadcastReceiver to listen when the alarm happens

public class NotificationReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {

   NotificationHelper notificationHelper = new NotificationHelper(context);
   notificationHelper.createNotification();

   }
}

I'm creating this class named NotificationReceiver and extends BroadcastReceiver, in onReceive there is Class named NotificationHelper, don't confuse i will explain this Class for next steps.

Step 3: Create the Notification class

class NotificationHelper {

 private Context mContext;
 private static final String NOTIFICATION_CHANNEL_ID = "10001";

 NotificationHelper(Context context) {
 mContext = context;
 }

void createNotification()
{

Intent intent = new Intent(mContext , NotificationActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
        0 /* Request code */, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);


NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Title")
        .setContentText("Content")
        .setAutoCancel(false)
        .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
        .setContentIntent(resultPendingIntent);

NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
    int importance = NotificationManager.IMPORTANCE_HIGH;
    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
    notificationChannel.enableLights(true);
    notificationChannel.setLightColor(Color.RED);
    notificationChannel.enableVibration(true);
    notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
    assert mNotificationManager != null;
    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
    mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

   }
}

This class handles the notification

Step 4: Come back to Step 2: and call the Notification Class

NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.createNotification();

Finally go to your AndroidManifest.xml and register this

<receiver android:name=".NotificationReceiver"/>

Upvotes: 1

Related Questions