我试图每15分钟触发一次通知,从我设置的时间开始。目前我的应用程序仅在我的应用程序打开时或最近的应用程序中通知,但当我关闭应用程序时,通知不再有效,但是当我再次打开应用程序时,它会触发通知。根据我的研究,我需要一个服务。所以我有3个文件。如何在后台触发通知?
在我的MainActivity,我设置报警
private void scheduleNotification(int week){
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra("notifId", getResources().getInteger(R.integer.notification_id));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, getResources().getInteger(R.integer.notification_id), notificationIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, week);
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
在MainActivity我叫一个BroadcastReceiver这是NotificationPublisher的。这里是我的NotificationPublisher的
public class NotificationPublisher extends BroadcastReceiver {
final String TAG = "NotificationPublisher";
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, NotificationAlarmService.class);
service.putExtra("notifId", intent.getIntExtra("notifId", 0));
context.startService(service);
}
然后我使用的BroadcastReceiver这是NotificationAlarmService启动服务,在这里,我建立使用NotificationCompat.Builder
的通知。
public class NotificationAlarmService extends Service {
. . . .
@Override
public int onStartCommand(Intent intent,int flag, int startId)
{
notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(this, intent.getIntExtra("notifId", 0), mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("App");
builder.setContentText("Notify Me");
builder.setAutoCancel(true);
builder.setSmallIcon(getNotificationIcon());
builder.setContentIntent(pendingIntent);
notificationManager.notify(intent.getIntExtra("notifId", 0), builder.build());
return super.onStartCommand(intent, flag, startId);
}
我已经尝试返回的START_STICKY
代替super.onStartCommand
我明白,当我使用的服务会在后台运行,即使用户关闭该应用程序。我也尝试更改this
并在服务中使用getBaseContext()
,但这不会触发通知。我不知道我是否错过了一些东西。先谢谢你。
编辑
这里是我的清单
<receiver android:name=".NotificationPublisher"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".NotificationAlarmService"
android:enabled="true">
</service>
我已经这样做了。 :(但它仍然不起作用,我还包括'android:enabled =“true”' –
好的..那么您是否还在清单中添加了Receiver? – cuppaBunny
是的,我已经添加了Receiver。 –