0
我試圖在上午9:00創建一個自動通知。定時通知(Android)的一些問題?
我創建了以下代碼,但我無法獲得自動通知。
而且,我在Android Manifest文件中添加了所需的權限。
在MainActivity.class
「onCreate
方法我調用的函數: setAlarm();
public void setAlarm() {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), Notifications.class);
alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 1001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar_now = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 30);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 1, alarmIntent);
if(calendar_now.getTimeInMillis() == calendar.getTimeInMillis()) {
new Notifications().createNotification(getApplicationContext(), getIntent(), "Stock-Market Alert", "The Market opens shortly.");
}
}
的Notifications.class如下:
public class Notifications extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String notificationTitle = "Default Title", notificationMessage = "Default Message";
createNotification(context, intent, notificationTitle, notificationMessage);
}
public void createNotification(Context context, Intent intent, String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1001,
new Intent(context, Repeating_activity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage)
.setTicker("Alert Message !")
.setAutoCancel(true)
.setSmallIcon(android.R.drawable.stat_sys_warning);
builder.setContentIntent(pendingIntent);
builder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
builder.setDefaults(NotificationCompat.DEFAULT_SOUND);
notificationManager.notify(1001, builder.build());
}
}
對不起仍然一無所獲。當我刪除時間約束並使用onClick(),通知出現,但沒有任何與我們上面的代碼:( –
是你的BroadcastReceiver在AndroidManifest.xml中聲明?嘗試發送一個Intent onClick()來檢查是否問題是AlarmManager或Receiver。 –
沒有問題。OnClick,通知的作品 –