我试图在一定时间间隔后从我的游戏发布通知。我从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);
任何人都可以告诉我哪里出错了。
答案 0 :(得分:1)
当您使用的Notification构造函数的参数仅用于显示目的。它不会延迟显示您的通知。
使用闹钟怎么样?但它只会接受意图。
答案 1 :(得分:1)
完全是理解的错误。查看public Notification (int icon, CharSequence tickerText, long when)
的详细信息。如下所示:
图标要放入状态栏的图标的资源ID。
tickerText 通知首次激活时状态栏中流动的文本。
何时在时间字段中显示的时间。在System.currentTimeMillis时基。
这意味着它仅用于通知按摩中的显示,而不是通知时间。如果您希望在将来某个时间发出通知,则必须为该时间设置AlermManager。 AlermManager将调用BroadcastReceiver。因此,您还必须创建一个BroadcastReceiver,您必须在其中设置通知。您可以通过此link。