[英]Android: Scheduled Notification doesn't show up?
我基本上是想在預定時間顯示每日通知(例如:每天7:30 AM)。 但是,我實現的代碼根本不顯示通知。
我設定時間的活動:
//This method is called by a button onClick method
private void SaveData() {
//I get the hour, minute and the AM/PM from 3 edittexts
String hours = hoursBox.getText().toString();
String minutes = minutesBox.getText().toString();
String ampm = ampmBox.getSelectedItem().toString();
if (hours.length() != 0 && minutes.length() != 0 && ampm.length() != 0) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours));
calendar.set(Calendar.MINUTE, Integer.parseInt(minutes));
calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.AM_PM, Calendar.AM);
Intent intent=new Intent(this, ReminderService.class);
AlarmManager manager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
PendingIntent pendingIntent=PendingIntent.getService(this, 0,intent, 0);
manager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),24*60*60*1000,pendingIntent);
}
}
ReminderService.java
public class ReminderService extends Service {
@Override
public void onCreate()
{
Intent resultIntent=new Intent(this, Dashboard.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification noti_builder= new Notification.Builder(this)
.setContentTitle("Hello from the other side!")
.setContentIntent(pIntent)
.setSmallIcon(R.drawable.helloicon)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti_builder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,noti_builder);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
我在這里做錯了什么? 我還應該在清單中添加任何內容嗎? 這是我目前僅有的兩種實現。 提前致謝!
您的應用中使用的任何Service
必須在清單中列出。 此外,由於您的Service
僅由您的應用使用,因此建議將exported
屬性設置為false
。
例如,在清單的<application>
標記內:
<service android:name=".ReminderService"
android:exported="false" />
此外, Calendar.HOUR_OF_DAY
上的部件Calendar
上設置一個24小時時鍾小時。 要使用12小時制,請使用Calendar.HOUR
並設置Calendar.AM_PM
組件。
最后,您將希望以某種方式獲得WakeLock
以確保即使手機未激活也可以發出Notification
。 WakeLock
自己動手使用WakeLock
,還有其他一些選擇。 v4支持庫中的WakefulBroadcastReceiver
類可用於啟動Service
,從中您可以通過信號通知Receiver完成后釋放鎖定。 另外,如果您不想添加Receiver組件,則可以簡單地用CommonsWare
的WakefulIntentService
類替換Service
。
如果您選擇使用WakefulBroadcastReceiver
,則您不打算將Service
更改為IntentService
,因為它不會進行任何長時間運行的操作,因為IntentService
會在完成工作時自行停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.