应用程序使用AlarmManager在特定时间启动

时间:2015-10-26 10:16:36

标签: android

我正在尝试使用AlarmManager在指定时间显示消息通知。我使用日历

设置日期
@Override
public void onReceive(Context context, Intent intent) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
    //Acquire the lock
    wl.acquire();

    //You can do the processing here.
    Bundle extras = intent.getExtras();
    StringBuilder msgStr = new StringBuilder();

    if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
        //Make sure this intent has been sent by the one-time timer button.
        msgStr.append("One time Timer : ");
    }
    Format formatter = new SimpleDateFormat("hh:mm:ss a");
    msgStr.append(formatter.format(new Date()));

    Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
    Log.d("AlarmManager", "onReceive");
    //Release the lock
    wl.release();
}

按下按钮

可触发以下功能
public void SetAlarm(Context context)
{
    Log.d("AlarmManager", "SetAlarm");
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    //After after 5 seconds
    //am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 2 , pi);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2015, 10, 26, 11, 58, 00);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
}

0 个答案:

没有答案