[英]Android notifications not getting posted when scheduled with AlarmManager
我试图在一定时间间隔后从我的游戏发布通知。 我从BroadcastReciever类的onReceive()方法调用PostNotification()函数,在开始游戏1分钟后发布通知。
广播接收器
public class NotificationReciever extends BroadcastReceiver
{
private static int count=0;
@Override
public void onReceive(Context context, Intent intent)
{
try
{
Bundle bundle = intent.getExtras();
String message = bundle.getString("message");
int id = bundle.getInt("id");
PostNotification(message, id);
}
catch (Exception e)
{
e.printStackTrace();
}
wl.release();
}
public void PostNotification(String notif, int id)
{
Notification notify=new Notification(R.drawable.icon,
notif,
System.currentTimeMillis());
Intent intent = new Intent(MyUtil.getInstance().context, MyActivity.class);
PendingIntent i=PendingIntent.getActivity(MyUtil.getInstance().context, 0, intent, 0);
notify.setLatestEventInfo(MyUtil.getInstance().context, "Title", notif, i);
MyActivity.notifyMgr.notify(id, notify);
}
}
}
我从MyActivity的onCreate()调用ScheduleNotification()
public void ScheduleNotification()
{
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(MyUtil.getInstance().context, NotificationReciever.class);
intent.putExtra("id", NOTIFY_ID);
intent.putExtra("message", "message");
PendingIntent sender = PendingIntent.getBroadcast(MyUtil.getInstance().context, NOTIFY_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
但我没有收到任何通知,并在我的logcat中收到以下错误
01-11 19:28:32.455: W/System.err(20661): java.lang.NullPointerException
01-11 19:28:32.475: W/System.err(20661): at android.content.ComponentName.<init>(ComponentName.java:75)
01-11 19:28:32.475: W/System.err(20661): at android.content.Intent.<init>(Intent.java:2893)
01-11 19:28:32.475: W/System.err(20661): at com.games.TestGame.NotificationReciever.PostNotification(NotificationReciever.java:41)
01-11 19:28:32.475: W/System.err(20661): at com.games.TestGame.NotificationReciever.onReceive(NotificationReciever.java:27)
我知道在创建通知意图时我做错了什么。 当我直接从我的活动打电话时,我得到了正确的通知,但是当我通过闹钟呼叫时出现了问题
Intent intent = new Intent(MyUtil.getInstance()。context,MyActivity.class);
任何人都可以告诉我哪里出错了。
您使用的Notification构造函数的when参数仅用于显示目的。 它不会延迟显示您的通知。
使用闹钟怎么样? 但它只接受一个意图。
理解是完全错误的。 查看public Notification (int icon, CharSequence tickerText, long when)
的详细信息public Notification (int icon, CharSequence tickerText, long when)
。 如下所示:
icon要放入状态栏的图标的资源ID。
tickerText通知首次激活时状态栏中流动的文本。
当时间显示在时间字段中。 在System.currentTimeMillis时基中。
这意味着它仅用于通知按摩中的显示,而不是通知时间。 如果您希望在将来某个时间发出通知,则必须为该时间设置AlermManager。 AlermManager将调用BroadcastReceiver。 所以你还必须创建一个BroadcastReceiver,你必须在其中设置Notification。你可以通过这个链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.