每周发送一次通知

Jol*_*lly 6 notifications android timer alarm

我想通知用户有关每周问题的答案.我需要将通知发送给用户,即使我的应用程序没有运行.通知将在一周内发送一次.当用户点击通知时,我的应用将会打开.我通过Timer和TimerTask()尝试了这个.这会在我的应用程序运行时通知用户.如何在应用程序未运行时将通知发送给用户.

有人可以帮帮我吗?

Pra*_*son 17

以下代码使用Alarmmanager和BroadcastReceiver,它将帮助您实现您的需求.

在您的活动中:

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);
Run Code Online (Sandbox Code Playgroud)

System.currentTimeInMillis() - 表示警报将在当前时间触发,您可以以毫秒为单位传递一天的常量时间.

然后创建一个这样的Receiver类,

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

您还必须在清单文件中注册BroadcastReceiver类,如下所示.在AndroidManifest.xml文件中,在内部标记中,

<receiver android:name="com.example.receivers.Receiver"></receiver>
Run Code Online (Sandbox Code Playgroud)

这里"com.example.receivers.Receiver"是我的包和我的接收者名字.