无法使用AlarmManager设置警报

时间:2013-03-07 10:49:31

标签: android alarmmanager alarm

我尝试了很多次但没有尝试过。

这是应该设置警报的类的代码,但在指定的小时和日期没有任何反应。

package com.beppe.reminder;

import java.util.Calendar;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.provider.AlarmClock;

public class ReminderManager {

private Context mCtx;
private AlarmManager alarm;



public ReminderManager(Context Ctx){
    mCtx=Ctx;

}


public void setAlarm(Date d, long taskID){

    alarm=(AlarmManager) mCtx.getSystemService(Context.ALARM_SERVICE);

    Intent intent=new Intent(mCtx, OnAlarm.class);
    intent.putExtra(DBAdapter.KEY_ROWID, taskID);

    PendingIntent pi=PendingIntent.getBroadcast(mCtx, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.clear();
    cal.set(d.getYear()+1900,d.getMonth(),d.getDate(),d.getHours(),d.getMinutes());


    alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
}

}

d.getYear()+1900行是因为Date类从1900年开始返回年份。

我尝试打印日期和时间,看起来是正确的(月份正确是从零开始的int)。

如果警报设置正确,我可以看到它吗?

1 个答案:

答案 0 :(得分:2)

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);                 

                //---get current date and time---
                Calendar calendar = Calendar.getInstance();       

                //---sets the time for the alarm to trigger---
                calendar.set(Calendar.YEAR, datePicker.getYear());
                calendar.set(Calendar.MONTH, datePicker.getMonth());
                calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());                 
                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
                calendar.set(Calendar.SECOND, 0);

                //---PendingIntent to launch activity when the alarm triggers---                    
                Intent i = new Intent("net.learn2develop.DisplayNotification");

                //---assign an ID of 1---
                i.putExtra("NotifID", 1);                                

                PendingIntent displayIntent = PendingIntent.getActivity(
                    getBaseContext(), 0, i, 0);               

                //---sets the alarm to trigger---
                alarmManager.set(AlarmManager.RTC_WAKEUP, 
                    calendar.getTimeInMillis(), displayIntent);
            }

请参阅此链接。  http://mobiforge.com/developing/story/displaying-status-bar-notifications-android