Time Event Listener

2019-02-07 13:41发布

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 practices? Event listener? Etc...

Expansion: I'm pretty new to Android development. I want to build a scheduling application which would control some features of the phone at pre-scheduled times. So let's say I schedule in the app to change from ring to vibrate at 3:00 and right now it's 2:00. So how do I capture the system time when it turns 3:00 to run that change?

I'm not sure whether any more information would be useful. I'm just trying to design this right now before I really get into developing it, so I'm looking for best practices and how to have an event listener run when the application is either running in the background or not running at all (if that's possible).

2条回答
仙女界的扛把子
2楼-- · 2019-02-07 14:27

Don't forget permissions:

    ....
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    ....
    AND broadcast receiver in application tag:        
    <receiver android:process=":remote" android:name="Alarm" />
  ....

Thanks

查看更多
唯我独甜
3楼-- · 2019-02-07 14:33

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:

....
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.VIBRATE"/>
....

and broadcast receiver in application tag:

<receiver  android:process=":remote" android:name="Alarm" />
查看更多
登录 后发表回答