Search code examples
androidandroid-notificationsandroid-alarms

Schedule a notification alarm in future in android


I'm new to Android development and have developed my first application.

I want to show notification to the user scheduled in background from date from database. I followed many tutorials on Google and this is what I have done.

I have created setAarm() function in Main Activity and a boradcast receiver class.

MainActivity.java

package com.example.myapp;

import ...


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    TextView navigationHeaderUserName;
    DatabaseHelper myDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        myDB = new DatabaseHelper(this);

        View header = navigationView.getHeaderView(0);
        navigationHeaderUserName = (TextView) header.findViewById(R.id.drawer_layout_user_name);

        // display dashboard when the activity is loaded
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, new ActivityDashboard());
        ft.commit();

        // set alarm
        setAlarm();
    }

    public void setAlarm() {

        // notification service
        boolean alarm = (PendingIntent.getBroadcast(this, 0, new Intent("ALARM"), PendingIntent.FLAG_NO_CREATE) == null);
        if (alarm) {
            Intent intentAlarm = new Intent("ALARM");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0);
            Calendar calendarAlarm = Calendar.getInstance();
            calendarAlarm.setTimeInMillis(System.currentTimeMillis());
            calendarAlarm.add(Calendar.SECOND, 3);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarAlarm.getTimeInMillis(), 6000, pendingIntent);
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        // calling the method displaySelectedScreen()
        displaySelectedScreen(item.getItemId());

        return true;
    }

    private void displaySelectedScreen(int itemId) {

       ....   // some code
       ....   // some code
    }
}

ActivityAlarmReceiver.java

    package com.example.myapp;

    import ...

public class ActivityAlarmReceiver extends BroadcastReceiver {

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

            DatabaseHelper db = new DatabaseHelper(context);
            String nextDate = db.getNextDate();

            if (nextDate == null) {
                return;
            }

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            SimpleDateFormat stf = new SimpleDateFormat("HH:MM:SS");

            String nextTime = "08:00:00";

            Date dateFormat = sdf.parse(nextDate);
            Date timeFormat = stf.parse(nextTime);

            Date today = new Date();

            if (dateFormat.equals(today)) {
                Intent intent1 = new Intent(context, MainActivity.class);
                createNotification(context, intent1, "New Message", "body!", "This is alarm");
            }
        } catch (Exception e) {
            Log.i("date", "error == " + e.getMessage());
        }
    }

    private void createNotification(Context context, Intent intent1, String ticker, String title, String description) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        builder.setTicker(ticker);
        builder.setContentTitle(title);
        builder.setContentText(description);
        builder.setSmallIcon(R.drawable.my_time_logo_transparent);
        builder.setContentIntent(pendingIntent);

        Notification n = builder.build();

        // create the notification
        n.vibrate = new long[]{150, 300, 150, 400};
        n.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(R.drawable.my_time_logo_transparent, n);

        // create a vibration
        try {
            Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone toque = RingtoneManager.getRingtone(context, som);
            toque.play();
        } catch (Exception e) {

        }
    }
}

But this is not working... I'm sure, I'm missing something but couldn't found what ??


Solution

  • This link (Scheduling Repeating Alarms) helps you. You must add into your Manifest the following code:

    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
    <receiver android:process=":remote" android:name=".ActivityAlarmReceiver"></receiver>