Android - How to set a notification to a specific date in the future?

eddielement picture eddielement · Jan 19, 2015 · Viewed 21.4k times · Source

Edit: SOLVED! Ever wanted to set a notification from a specific date starting a certain point in time (when an activity is started or when a button is pressed?) Read more to find out how:

 //Set a notification in 7 days
                Calendar sevendayalarm = Calendar.getInstance();

                sevendayalarm.add(Calendar.DATE, 7);

                Intent intent = new Intent(this, Receiver.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 001, intent, 0);

                AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
                am.set(AlarmManager.RTC_WAKEUP, sevendayalarm.getTimeInMillis(), pendingIntent);

Here's the code for the Receiver class

public class Receiver extends Service {

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

    @Override
    public void onCreate() {
        Intent intent = new Intent(this, Test.class);
        long[] pattern = {0, 300, 0};
        PendingIntent pi = PendingIntent.getActivity(this, 01234, intent, 0);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.depressiontest)
            .setContentTitle("Take Questionnaire")
            .setContentText("Take questionnaire for Duke Mood Study.")
            .setVibrate(pattern)
            .setAutoCancel(true);

        mBuilder.setContentIntent(pi);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(01234, mBuilder.build());
    }
}

And don't forget to add the below permissions in the manifest!

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
 <service android:name=".Receiver2" android:enabled="true">
        <intent-filter> <action android:name="NOTIFICATION_SERVICE" /></intent-filter>
    </service>

Answer

King of Masses picture King of Masses · Jan 19, 2015

Don't forget to give the below manifest permissions

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Your broadcast receiver registrations would be like this

   <receiver android:name=".AlarmReceiver" >
         <intent-filter>
           <action android:name="NOTIFICATION_SERVICE" />
         </intent-filter>
     </receiver>