我将重复时间设置为5秒.第一次吐司在5秒后出现,但下一次在1分钟后重复一次.
我也尝试了使用setRepeating()的代码,它仍然不起作用.
这是我的代码:
public void constructJob(){ Intent alertIntent = new Intent(this, AlarmManagerService.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this, 0, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, GregorianCalendar.getInstance().getTimeInMillis(), repeatTime(), pendingIntent ); } public long repeatTime(){ return 5000; }
AlarmManagerService.java
public class AlarmManagerService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "5 seconds have passed", Toast.LENGTH_SHORT).show(); }
ctate.. 17
文档需要更新.截至我认为Android 5.1(API版本22),重复警报的最短时间为1分钟,未来警报的设置时间不能少于5秒.
如果您需要在一分钟内完成工作,只需直接设置闹钟,然后从该闹钟的处理程序中设置下一个闹钟等.
如果您需要在5秒内完成工作,请将其发布到处理程序而不是使用警报管理器?
文档需要更新.截至我认为Android 5.1(API版本22),重复警报的最短时间为1分钟,未来警报的设置时间不能少于5秒.
如果您需要在一分钟内完成工作,只需直接设置闹钟,然后从该闹钟的处理程序中设置下一个闹钟等.
如果您需要在5秒内完成工作,请将其发布到处理程序而不是使用警报管理器?
不要使用setRepeating()或setInExactRepeating,它不会在5秒后重复.相反,尝试安排一次警报,然后在onReceive()方法中再次重新安排它,就像这样.这将在特定时间间隔后重复(在这种情况下为5秒)
MainActivity.java
public class MainActivity extends AppCompatActivity { Button btnStartAlarm, btnStopAlarm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnStartAlarm = (Button) findViewById(R.id.btnStartAlarm); btnStopAlarm = (Button) findViewById(R.id.btnStopAlarm); Intent intent = new Intent(MainActivity.this, AlarmReceiver.class); final PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, 0); final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); btnStartAlarm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent); } }); btnStopAlarm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alarmManager.cancel(pendingIntent); } }); } }
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver { public AlarmReceiver() { } @Override public void onReceive(Context context, Intent intent) { Log.d("Javed", "onReceive called"); Toast.makeText(context, "onReceive called", Toast.LENGTH_LONG).show(); Intent intent1 = new Intent(context, AlarmReceiver.class); final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 100, intent1, 0); final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent); } }