我有一个%
,应该每天在确切的时间发送application
。它可以随时触发,但每当我关闭应用notifications
时,它就会出现。
通知类:
notification
MainActivity:
@Override
public int onStartCommand(Intent intent,int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Context context = getApplicationContext();
Intent resultIntent = new Intent(getApplicationContext(), Love.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, resultIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
/* Invoking the default notification service */
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentIntent(contentIntent);
android.app.Notification notification = mBuilder.build();
notification.defaults = notification.DEFAULT_SOUND |
notification.DEFAULT_VIBRATE;
notification.flags |= notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
return Service.START_STICKY;
}
和BroadcastReceiver:
公共类AlarmReceiver扩展了BroadcastReceiver {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 10);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
long day = TimeUnit.HOURS.toMillis(24);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),day, pendingIntent);
接收器:
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, Notification.class);
context.startService(service1);
}
}
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, Notification.class);
context.startService(service1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Boolean notif = sharedPreferences.getBoolean("notif", true);
if (!notif) context.stopService(service1);
}
必须仅在10:00发送,但它的行为非常奇怪,方法Notification
每次都不起作用(如果甚至是假的话)。我想这是带有旗帜的东西,但我仍然不知道我究竟做错了什么。
提前致谢。而且,请不要忘记我的问题,即使它很容易或只是愚蠢。我是新手,只是想知道。
答案 0 :(得分:1)
完成后你只需要销毁服务:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
stopSelf()
return Service.START_STICKY;