Android:setAlarmManager(...)打开一个活动而不是延迟开放

时间:2014-11-26 08:01:01

标签: android android-activity alarmmanager synchronize

在Android中,我必须在特殊时刻设置闹钟,以便在当天的正确时间响铃并打开活动。

我的问题是功能“alarmManager.set(...)” OPEN INSTANTLY 目标活动,当达到时间时,再次打开相同的活动。

我不明白为什么会发生这种情况我该怎么纠正呢?

当前状态:我有一个时间戳,帮助我选择时间。我还有一个按钮,当我点击它时,通过从时间戳中检索时间并以毫秒为单位计算下一个警报来调用函数alarmManager.set()。

THX

按钮代码:

public void setTheAlarm(View view) {

    TimePicker tp_clock = (TimePicker) findViewById(R.id.tp_timeToRing);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int alarmHours = tp_clock.getCurrentHour();
    int alarmMinutes = tp_clock.getCurrentMinute();

    Toast.makeText(this, "Alarm set for " + alarmHours + "h" + alarmMinutes, Toast.LENGTH_LONG).show();

    Long time = calculateTime(alarmHours, alarmMinutes);
    alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}

函数的代码calculateTime:

public Long calculateTime(int alarmHours, int alarmMinutes) {

    Calendar c = Calendar.getInstance();
    int currentHours = c.get(Calendar.HOUR);
    if (c.get(Calendar.AM_PM) == 1)
        currentHours +=12;
    int currentMinutes = c.get(Calendar.MINUTE);
    int setAlarmHours = 0;
    int setAlarmMinutes = 0;
    int balanceWithMinute = 0;

    if (alarmMinutes >= currentMinutes) {

        setAlarmMinutes = alarmMinutes - currentMinutes;
    }
    else {

        setAlarmMinutes = (60 - currentMinutes) + alarmMinutes;
        balanceWithMinute = 1;
    }
    if (alarmHours > currentHours)
        setAlarmHours = alarmHours - currentHours;

    if (alarmHours < currentHours)
        setAlarmHours = (24 - currentHours) +alarmHours - balanceWithMinute;

    if (alarmHours == currentHours && balanceWithMinute == 1)
        setAlarmHours = 23;

    Long time = new GregorianCalendar().getTimeInMillis()+setAlarmHours*setAlarmMinutes*60*1000;
    return time;
}

alarmManager的代码:

package fr.pixelcraft.victor.wackertest.SoundPackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import fr.pixelcraft.victor.wackertest.LoginActivity;

public class AlarmReciever extends BroadcastReceiver {

    private String userToken;
    private String userId;

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent i=new Intent(context, PlanASoundActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        userToken = intent.getStringExtra(LoginActivity.USER_TOKEN);
        userId = intent.getStringExtra(LoginActivity.USER_ID);

        i.putExtra(LoginActivity.USER_TOKEN, userToken);
        i.putExtra(LoginActivity.USER_ID, userId);
        context.startActivity(i);

        Toast.makeText(context, "Alarm triggered", Toast.LENGTH_LONG).show();
    }
}

1 个答案:

答案 0 :(得分:0)

https://stackoverflow.com/users/2649012/frank-n-stein

可能你设定的时间已经过去了。这会使AlarmManager立即触发。 -