每周发送一次通知 [英] Send notification once in a week
问题描述
我想通知用户回答每周问题.即使我的应用程序没有运行,我也需要向用户发送通知.通知将在一周内发送一次.当用户单击通知时,我的应用程序将打开.我通过 Timer 和 TimerTask() 尝试了这个.这会在我的应用程序运行时通知用户.如何在应用程序未运行时向用户发送通知.
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 user clicks the notification my app will gets open. I tried this via Timer and TimerTask().This notifies the user when my app is running.How can I send the notification to the user while app is not running.
有人可以帮我吗?
推荐答案
以下代码将 Alarmmanager 与 BroadcastReceiver 结合使用,这将帮助您实现您的需求.
The following code uses Alarmmanager with BroadcastReceiver which will help you out achieving your need.
在您的活动中:
Intent intent = new Intent(MainActivity.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, System.currentTimeInMillis(), am.INTERVAL_DAY*7, pendingIntent);
System.currentTimeInMillis() - 表示警报将在当前时间触发,您可以以毫秒为单位传递一天的恒定时间.
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,
public class Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
public void showNotification(Context context) {
Intent intent = new Intent(context, AnotherActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, reqCode, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.android_icon)
.setContentTitle("Title")
.setContentText("Some text");
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(reqCode, mBuilder.build());
}
}
此外,您还必须在清单文件中注册您的 BroadcastReceiver 类,如下所示.在您的 AndroidManifest.xml 文件中,标签内,
Also you have to register your BroadcastReceiver class in your manifest file, like the following. In your AndroidManifest.xml file, inside tag,
<receiver android:name="com.example.receivers.Receiver"></receiver>
这里的com.example.receivers.Receiver"是我的包裹和我的接收者名称.
Here "com.example.receivers.Receiver" is my package and my receiver name.
这篇关于每周发送一次通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!