App被销毁后立即发出通知

时间:2014-07-26 09:31:26

标签: android notifications broadcastreceiver alarmmanager repeatingalarm

我已经设置了一个通知,该通知将在应用程序被销毁后4小时显示。

但是当我正在销毁应用程序时,通知会立即发出,也会在4小时后发出。

这是我的主要活动的onDestroy():

@Override
    public void onDestroy() {
        super.onDestroy();


        Intent myIntent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        //alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
    }

,这是我的AlarmReceiver.class:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent mainIntent = new Intent(context, Main.class);

        NotificationManager notificationManager
            = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        android.app.Notification noti = new NotificationCompat.Builder(context)
            .setAutoCancel(true)
            .setContentIntent(PendingIntent.getActivity(context, 0, mainIntent,
                              PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentTitle("Title")
            .setContentText("It's been so Long!!!")
            .setSubText("Please return back to App & Learn more Duas.")
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setVibrate(new long[] {700,700,700,700})
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Important Notification")
            .setWhen(System.currentTimeMillis())
            .build();

        notificationManager.notify(0, noti);
    }

}

我希望每4个小时后显示一次通知&并没有立即销毁App。

任何帮助都会得到高度赞赏。

先谢谢。

1 个答案:

答案 0 :(得分:1)

这是因为小错误

只需更改此行

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);

到此

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()+(3600*1000*4)), 3600*1000*4, pendingIntent);