1
我在這裏閱讀了幾個問題,並且也有類似的問題。不幸的是,在另一個問題上的答案能夠解決這個問題。我知道如何在按鈕上單擊創建通知,但我未能在特定時間創建通知。我在下面的代碼片段中的目標是每天在19:00創建一個通知。以下是代碼片段:在預定義時間發送通知不起作用
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
setAlarm(calendar);
}
public void setAlarm(Calendar calendar) {
Intent alertIntent = new Intent(this, Receiver.class);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, alertIntent, 0);
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 00);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
24*60*60*1000, pendingIntent);
}
接收機:
public class Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "Blabla", "Blablablabla", "Alert");
}
public void createNotification(Context context, String msg,
String msgText, String msgAlert) {
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.clear_dayicon)
.setContentTitle(msg)
.setContentText("msgText")
.setTicker(msgAlert);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
清單:
// only ones I called after started working with notifications and stuff
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<service android:name=".Receiver2" android:enabled="true">
<intent-filter> <action android:name="NOTIFICATION_SERVICE" /></intent-filter>
</service>
<receiver android:name=".Receiver"/>
有些幫助將是非常讚賞。由於我是初學者,我需要有人向我展示自己的錯誤。否則,無論我讀了多少文檔,我都無法發現它們。此代碼看起來好像沒什麼問題:P
.getService()來.getBroadcast()是我猜的問題。感謝您的改進。 –