如何在android studio上设置闹钟?

时间:2016-04-15 16:57:25

标签: android alarmmanager

我真的需要帮助的人,我试图在特定时间与Android的警报管理器一起出现。我做了一些研究,我制作了这段代码,但我不知道什么不行......我尝试了一切

public void start() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Date dat = new Date();
        Calendar cal_alarm = Calendar.getInstance();
        Calendar cal_now = Calendar.getInstance();
        cal_now.setTime(dat);
        cal_alarm.setTime(dat);
        cal_alarm.set(Calendar.HOUR_OF_DAY,12);
        cal_alarm.set(Calendar.MINUTE,13);
        cal_alarm.set(Calendar.SECOND,0);
        if(cal_alarm.before(cal_now)){
            cal_alarm.add(Calendar.DATE,1);
        }
        manager.set(AlarmManager.RTC_WAKEUP,cal_alarm.getTimeInMillis(),pendingIntent);
    }

如果我在manager.set中使用cal_alarm - cal_now,它会在5秒后触发。

1 个答案:

答案 0 :(得分:3)

您需要添加Receiver才能获得结果

AndroidManifest.xml 中添加此

<receiver android:name=".AlarmReceiver" />

创建此BroadcastReceiver AlarmReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

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

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

最后,修复你的方法开始

public void start() {
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Date dat = new Date();
    Calendar cal_alarm = Calendar.getInstance();
    Calendar cal_now = Calendar.getInstance();
    cal_now.setTime(dat);
    cal_alarm.setTime(dat);
    cal_alarm.set(Calendar.HOUR_OF_DAY,14);
    cal_alarm.set(Calendar.MINUTE,18);
    cal_alarm.set(Calendar.SECOND,0);
    if(cal_alarm.before(cal_now)){
        cal_alarm.add(Calendar.DATE,1);
    }

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

    manager.set(AlarmManager.RTC_WAKEUP,cal_alarm.getTimeInMillis(), pendingIntent);
}