我想使用服务每小时或特定秒显示本地通知,我尝试实现此功能,但没有成功。
我的代码如下所示
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
Log.d("day for notification:::", String.valueOf(notification_day));
cal.add(Calendar.MINUTE, notification_day);
alarmManager.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 4 * 60 * 60, broadcast);
最佳答案
你的代码看起来没问题。 唯一可能出现问题的是间隔 4*60*60 太短,为 14.4 秒。
此外,您似乎没有将 Intent 定向到特定的接收者。你应该这样做:
Calendar calendar = Calendar.getInstance();
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)this.getSystemService(this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60, pendingIntent);
你应该捕获它:
public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, EVentsPerform.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.applogo)
.setContentTitle("text")
.setContentText("text")
.setWhen(when)
.setContentIntent(pendingIntent)
notificationManager.notify(yourId, mNotifyBuilder.build());
}
}
将其添加到您的 list 文件中:
<!-- permission required to use Alarm Manager -->
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<!-- Register the Alarm Receiver -->
<receiver android:name="com.example.alarmmanagernotifcation.AlarmReceiver"/>
关于android - 如何使用服务每小时显示本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861271/