[英]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.