Time Event Listener

后端 未结 2 1680
走了就别回头了
走了就别回头了 2021-01-01 05:44

My Question: How do I have my application do something at a certain time? Especially in a case when it\'s not technically running (is that possible). Best p

2条回答
  •  温柔的废话
    2021-01-01 06:20

    You can use a pendingIntent with a BroadCastReceiver like this:

    Calendar cal = Calendar.getInstance();
    Intent activate = new Intent(context, Alarm.class);
    AlarmManager alarms ;
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, activate, 0);
    alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minute);
    cal.set(Calendar.SECOND, 00);
    alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
    

    Then the BroadCast Receiver:

    public class Alarm extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
          MediaPlayer mp = MediaPlayer.create(context, R.raw.ferry_sound);
          mp.start();
          PowerManager pm = (PowerManager)     context.getSystemService(Context.POWER_SERVICE);
          PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
          wl.acquire();
          Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
          long[] s = { 0, 100, 10, 500, 10, 100, 0, 500, 10, 100, 10, 500 };
          vibrator.vibrate(s, -1);
       }
    }
    

    Don't forget to include these permissions in your AndroidManifest.xml:

    ....
    
    
    ....
    

    and broadcast receiver in application tag:

    
    

提交回复
热议问题