我正在向我的应用添加通知,如果应用关闭,Everyting工作正常,它会按照我想要的方式触发通知,但是当我启动应用时,在创建时称为通知触发。如果我离开应用并再次启动应用,则会再次触发通知。
然而,当我打开我的应用程序通知时会发生火灾。我不希望这种行为。
这是用于通知的代码,我将代码放在onCreate
中:
我知道我应该从onCreate
移动它,但移动它的位置?
是否可以检查已经设置的警报,如果是,则不再发射通知。
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000 , 1000 * 60 * 45, pendingIntent);
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent: ");
Realm realm = null;
try{
realm = Realm.getDefaultInstance();
RealmResults<Drop> results = realm.where(Drop.class).equalTo("completed", false).equalTo("deleted", false).findAll();
for(Drop current : results){
if(isNotificationNeeded(current.getAdded(), current.getWhen(), current.isSwitchButtonchecked())){
fireNotification(current);
}
}
} finally {
if(realm!=null){
realm.close();
}
}
}
&#13;
public class NotificationService extends IntentService {
public static final String TAG = "holaa";
private long vrijemeStartAlarmUDevetSati = 1000*60*60*9; //milisecunds*secoonds*min*hours* - from 9h
private long vrijemeAlarmDoJedanestSati = 1000*60*60*23; //milisecunds*secoonds*min*hours* - to 23h
Bundle bundle;
int i = 0;
public NotificationService() {
super("NotificationService");
Log.d(TAG, "NotificationService: ");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent: ");
//realm database
Realm realm = null;
try{
realm = Realm.getDefaultInstance();
RealmResults<Drop> results = realm.where(Drop.class).equalTo("completed", false).equalTo("deleted", false).findAll();
for(Drop current : results){
if(isNotificationNeeded(current.getAdded(), current.getWhen(), current.isSwitchButtonchecked())){
fireNotification(current);
}
}
} finally {
if(realm!=null){
realm.close();
}
}
}
private void fireNotification(Drop drop) {
i = i+1;
String messageTitle = drop.getWhat();
String messageNote = drop.getWhat_note();
int ikonicaBojaNota = drop.getColorPickerRoudIcon();
PugNotification.with(this)
.load()
.identifier(i)
.title(messageTitle)
.message(messageNote)
.bigTextStyle(messageNote)
.smallIcon(R.drawable.ic_drop)
.largeIcon(R.drawable.logo)
.flags(Notification.DEFAULT_ALL)
.autoCancel(true)
.click(Main2Activity.class, bundle)
.color(color)
.simple()
.build();
}
private boolean isNotificationNeeded(long added, long when, boolean switchButtonchecked){
long now = System.currentTimeMillis();
if ((now>when+ vrijemeStartAlarmUDevetSati) && (now < (when + vrijemeAlarmDoJedanestSati)) && switchButtonchecked == true){
bundle = new Bundle();
bundle.putLong("notification", added);
return true;
}
else {
//do nothing
return false;
}
}
}
&#13;
答案 0 :(得分:1)
启动服务与创建通知无关。您的活动应该只启动该服务。它不应该创建任何通知。服务启动后,它负责创建通知。