0

So, im working on making daily notifications for my app. And it works somehow, but the problem is that everytime i start the app or restart, it starts a notification randomly. Its just really frustating.

I've been going trough the code many times, and i just cant see why its happens

So here is everything that have to do with notifications

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    public NavigationView navigationView;

    private NotificationManagerCompat notificationManager;

    SharedPreferences preferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Notifications
        preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);

        SetNotification();
    }


    public void SetNotification(){
            if (GetNotificationsChecked()){
                Intent notificationIntent =new Intent(this,Notification_Reciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);

                AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

               Calendar calendar = Calendar.getInstance();
               calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
               calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;


                if (manager != null) {
                    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,  pendingIntent);
                }

            }
        }


    public boolean GetNotificationsChecked(){
        boolean i = preferences.getBoolean("notifications", true);
        return i;

    }

}

Notification_reciever.java

public class Notification_Reciever extends BroadcastReceiver {

    private NotificationManagerCompat notificationManagerCompat;

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

        Intent activityIntent = new Intent(context, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context,
                0, activityIntent, 0);

        notificationManagerCompat = NotificationManagerCompat.from(context);

        Notification notification = new NotificationCompat.Builder(context,CHANNEL_1_ID)
                .setSmallIcon(R.drawable.ic_face)
                .setContentTitle("Your Daily Life Tip!")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_ALARM)
                .setContentIntent(contentIntent)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .setSummaryText("Daily Notification"))
                .setAutoCancel(true)
                .setContentText(getlifetip(context))
                .setColor(Color.parseColor("#EE3D33"))
                .build();
        notificationManagerCompat.notify(0, notification);

    }

    public String getlifetip(Context context){
          //gets lifetip from jsonobject

}

MyService.java

public class MyService extends Service {
    SharedPreferences preferences;
    public MyService(){

    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SetNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null){
            SetNotification();
        }else Toast.makeText(this, "Intent was null", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags,startId);
    }
    public void SetNotification(){
        preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
        if (GetNotificationsChecked()){
            Intent notificationIntent =new Intent(this,Notification_Reciever.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            try{
                manager.cancel(pendingIntent);

            }catch (Exception ignored){}

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
            calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;


            if (manager != null) {
                manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,  pendingIntent);
            }

        }
    }
    public boolean GetNotificationsChecked(){
        boolean i =  preferences.getBoolean("notifications", true);
        return i;

    }

}

BootReciever.java

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context,MyService.class);
        context.startService(i);
    }
}

App.java


public class App extends Application {

    public static final String  CHANNEL_1_ID = "dailylifetip";

    @Override
    public void onCreate() {
        super.onCreate();


        CreateNotificationChannel();
    }
    private void CreateNotificationChannel(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel1 = new NotificationChannel(
                    CHANNEL_1_ID,
                    "Daily Life Tips",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is the daily life tips channel");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
        }
    }
}

Manifest

    <receiver android:name=".Notification_Reciever"/>
        <service android:name=".MyService" android:enabled="true" android:exported="true"/>

The user selects the hour and minute of the day in an options menu, and is saved in preferences. And then should give an notification everyday on that time. And that works!. But everytime you open the app it randomly sends you a notifications, there is no errors.

eleven
  • 6,779
  • 2
  • 32
  • 52
  • Every time `MainActivity` is created, you're resetting the alarm, and if the time in your `Calendar` has already passed today, then the first alarm time is in the past, so it fires pretty much immediately. You can check if you've already set the alarm by checking if that specific `PendingIntent` already exists. To do that, first make that same `PendingIntent.getBroadcast()` call, but pass `PendingIntent.FLAG_NO_CREATE` instead. If that returns null, then you can create it with `FLAG_ONE_SHOT` and set your alarm. – Mike M. Aug 08 '19 at 12:39
  • No problem. I just realized, though, that I forgot to consider that first alarm time after a reboot. To make sure you don't set an alarm in the past, you should also check if the time in your `Calendar` is before the current time, and add a day if it is, like is shown in [this answer](https://stackoverflow.com/a/36536228). That by itself would've "fixed" your original issue, but you would've been needlessly resetting the alarm each run. I'd say it's probably preferable to do both checks. Anyhoo, glad you got it working. Cheers! – Mike M. Aug 08 '19 at 13:21

0 Answers0