AlarmManager仅在应用程序重启

时间:2015-06-20 19:19:58

标签: android service notifications alarmmanager

我制作了一个AlarmManager,它在特定的时间和每30分钟后启动一次服务。服务开始通知。问题是,我在重新启动应用程序后才收到通知。通知有效,但AlarmManger没有,因为我在重新启动应用程序后每次都收到通知。重新启动应用程序并不重要,我每次都会收到通知。

继承我的AlarmManger代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Intent myIntent = new Intent(MainActivity.this , MyAlarmService.class);
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 19);
    calendar.set(Calendar.MINUTE, 4);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
}

这是我的通知代码:

public class MyAlarmService extends Service {

@Override

public void onCreate() {

    Intent intent1 = new Intent(this, MainActivity.class);
    intent1.putExtra("EXTRA_EVENT_ID", 101);
    PendingIntent pI = PendingIntent.getActivity(this, 0, intent1, 0);
    Notification noti =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.logo)
                    .setContentTitle(gr)
                    .setContentText(r)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setStyle(bigStyle)
                    .extend(wearableExtender)
                    .build();

    NotificationManagerCompat nM = NotificationManagerCompat.from(this);
    nM.notify(0,noti);
}

1 个答案:

答案 0 :(得分:1)

尝试将alarmManager设置为setRepeating(),如此

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        (30*60*1000), pendingIntent);