Skip to content Skip to sidebar Skip to footer

Send Notification Once In A Week

I want to notify the user about answer the weekly questions.I need to send the notification to the user even my app is not running.The notification will send once in a week. When

Solution 1:

The following code uses Alarmmanager with BroadcastReceiver which will help you out achieving your need.

In your activity:

Intentintent=newIntent(MainActivity.this, Receiver.class);
PendingIntentpendingIntent= PendingIntent.getBroadcast(MainActivity.this, REQUEST_CODE, intent, 0);
AlarmManageram= (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, System.currentTimeInMillis(), am.INTERVAL_DAY*7, pendingIntent);

System.currentTimeInMillis() - denotes that the alarm will trigger at current time, you can pass a constant time of a day in milliseconds.

Then create a Receiver class something like this,

publicclassReceiverextendsBroadcastReceiver{
    @OverridepublicvoidonReceive(Context context, Intent intent) {
        showNotification(context);
    }

    publicvoidshowNotification(Context context) {
        Intentintent=newIntent(context, AnotherActivity.class);
        PendingIntentpi= PendingIntent.getActivity(context, reqCode, intent, 0);
        NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.android_icon)
            .setContentTitle("Title")
            .setContentText("Some text");
        mBuilder.setContentIntent(pi);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManagermNotificationManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(reqCode, mBuilder.build());
    }
}

Also you have to register your BroadcastReceiver class in your manifest file, like the following. In your AndroidManifest.xml file, inside tag,

<receiverandroid:name="com.example.receivers.Receiver"></receiver>

Here "com.example.receivers.Receiver" is my package and my receiver name.

Post a Comment for "Send Notification Once In A Week"