如何在指定时间内设置alarmManager

时间:2016-09-20 05:55:21

标签: android

我正在开发一个应用程序,我必须在完成7天后显示通知我计算结束日期和时间。

但我不知道如何在闹钟管理器中设置此功能,并且还希望在指定时间后使闹钟管理器失效。

我的代码是:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, 7);

    /*Getting Day and Time When request will send to server*/
    endDay = String.valueOf(c.get(Calendar.MONTH) + 1) + "/" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/" +
            String.valueOf(c.get(Calendar.YEAR));
    Log.e(TAG, "End Day::" + endDay);

    endTime = String.valueOf(c.get(Calendar.HOUR_OF_DAY)) + ":" +
            String.valueOf(c.get(Calendar.MINUTE)) + ":" + String.valueOf(c.get(Calendar.SECOND));
    Log.e(TAG, "End Time::" + endTime);


    StringTokenizer tokens = new StringTokenizer(endDay, "/");
    String month = tokens.nextToken().trim();
    int month1 = Integer.parseInt(month);
    int month2 = month1 - 1;
    String day = tokens.nextToken().trim();
    String year = tokens.nextToken().trim();


    StringTokenizer tokens1 = new StringTokenizer(endTime, ":");
    String hour = tokens1.nextToken().trim();
    String min = tokens1.nextToken().trim();
    String second = tokens1.nextToken().trim();

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, month2);
    calendar.set(Calendar.YEAR, Integer.parseInt(year));
    calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));

    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
    calendar.set(Calendar.MINUTE, Integer.parseInt(min));
    calendar.set(Calendar.SECOND, Integer.parseInt(second));
    calendar.set(Calendar.AM_PM, Calendar.AM);

    Log.e(TAG, "End Day::" + endDay);
    Log.e(TAG, "End Time::" + endTime);

    Log.e(TAG, "Month::" + month);
    Log.e(TAG, "Day::" + day);
    Log.e(TAG, "Hour::" + hour);
    Log.e(TAG, "Min::" + min);
    Log.e(TAG, "Second::" + second);

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

1 个答案:

答案 0 :(得分:0)

  AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  Intent intent = new Intent(context, YOURSERVICECLASS.class);
  PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent, 0);
  alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, 5000, 1000 * 5 * 60, alarmIntent);//YOU CAN CHANGE TIME HERE