/** 停止循环 */ public static void stopLoop(int requestCode) { if (mApp == null) { return; } LoopRunnable loopRunnable = sLoopRunnerMap.get(requestCode); sLoopRunnerMap.remove(requestCode); Intent intent = new Intent(ACTION_LOOP); intent.putExtra("requestCode", requestCode); AlarmManager alarmManager = (AlarmManager) mApp.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getBroadcast(mApp, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.cancel(pendingIntent); if (loopRunnable != null) { loopRunnable.loopEnd(); } }
/** * 循环 TODO 建议使用JobScheduler替代循环方法 * * @param runnable * @param frequency */ public static void loop(String name, LoopRunnable runnable, long frequency) { if (mApp == null || runnable == null) { return; } int requestCode = StringUtils.translateToInt(name); stopLoop(requestCode); Logger.d("request [" + name + "] hash code " + requestCode); sLoopRunnerMap.put(requestCode, runnable); runnable.run(); Intent intent = new Intent(ACTION_LOOP); intent.putExtra("requestCode", requestCode); AlarmManager alarmManager = (AlarmManager) mApp.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getBroadcast(mApp, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + frequency, frequency, pendingIntent); }