每次应用启动时,Android AlarmManager都会发送通知,而不是仅发送一次

时间:2016-01-02 18:29:07

标签: android notifications alarmmanager

我的应用使用启动var List = React.createClass({ deleting: function(test) { console.log(test); }, render: function() { var all = this.props.activities; var list = all.map(function(a) { return (<ListItem key={a} act={a} del={this.deleting} />); }, this); return <ul> {list} </ul> } }); 的{​​{1}}。 AlarmManager会向用户生成提醒通知。

这是启动警报的MainActivity

BroadcastReceiver

这是生成通知的BroadcastReceiver

public class MainActivity extends ActionBarActivity {

    private PendingIntent pendingIntent;
    private AlarmManager alarmManager;

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

        // Set the alarm to start at approximately 2:00 p.m.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int curHr = calendar.get(Calendar.HOUR_OF_DAY);

// Checking whether current hour is over 14
        if (curHr >= 14)
        {
            // Since current hour is over 14, setting the date to the next day
            calendar.add(Calendar.DATE, 1);
        }

        calendar.set(Calendar.HOUR_OF_DAY, 14);
// Schedule alarm manager

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

        alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

        // With setInexactRepeating(), you have to use one of the AlarmManager interval
        // constants--in this case, AlarmManager.INTERVAL_DAY.
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pendingIntent);


    }

清单权限:

BroadcastReceiver

如您所见,警报必须在下午14点开始,但每次启动应用程序时都会收到通知。 我的代码有问题吗?

我使用Scheduling Repeating Alarms每天在同一时间设置闹钟,但无法正常工作

1 个答案:

答案 0 :(得分:2)

问题是您要将时间设置为当天。因此,如果您在14:00之后打开您的应用程序,您的警报管理器将立即触发。

您需要检查当天的时间是否超过14:00,如果是,则需要将日期更改为第二天:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);

// Checking whether current hour is over 14
if (curHr >= 14)
{
   // Since current hour is over 14, setting the date to the next day
   calendar.add(Calendar.DATE, 1);
}

calendar.set(Calendar.HOUR_OF_DAY, 14);
// Schedule alarm manager