public class MyFirebaseMessagingServices extends FirebaseMessagingService {
private NotificationChannel mChannel;
private NotificationManager notifManager;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
try {
JSONObject jsonObject = new JSONObject(remoteMessage.getData());
displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void displayCustomNotificationForOrders(String title, String description) {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService
(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder;
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (mChannel == null) {
mChannel = new NotificationChannel
("0", title, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(this, "0");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentTitle(title)
.setSmallIcon(getNotificationIcon()) // required
.setContentText(description) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource
(getResources(), R.mipmap.logo))
.setBadgeIconType(R.mipmap.logo)
.setContentIntent(pendingIntent)
.setSound(RingtoneManager.getDefaultUri
(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notifManager.notify(0, notification);
} else {
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = null;
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(description)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
.setSound(defaultSoundUri)
.setSmallIcon(getNotificationIcon())
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1251, notificationBuilder.build());
}
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
}
}
@ECHO OFF
SETLOCAL
SET "targetdir=U:\destdir"
SET /a retain=10
FOR /f "skip=%retain%delims=" %%a IN (
'dir /b /a-d /o-d "%targetdir%\*" '
) DO ECHO (DEL "%targetdir%\%%a"
GOTO :EOF
Вам нужно будет изменить настройку targetdir
в соответствии с вашими обстоятельствами. Точно так же эта процедура предназначена для всех файлов - измените маску файла.
Необходимые команды DEL просто ECHO
ed для целей тестирования. После того, как вы подтвердите правильность команд, измените ECHO(DEL
на DEL
, чтобы фактически удалить файлы.
метод состоит в том, чтобы просто выполнить dir
в базовой форме без каталогов, отсортированных в обратном порядке -date order.
Пропустить первые 10 записей и удалить остальные.
С forfiles
я не вижу возможности выполнить вашу задачу по возвращению новейшего (самого последнего) количества файлов.
Итак, моя идея для этого подхода такова:
dir /B /A:-D /T:C /O:-D
для извлечения голого списка (/B
) файлов (без каталогов, /A:-D
), отсортированных по дате создания (/T:C
; если вы хотите использовать последнюю дату модификации, просто удалите /T:C
) в порядке убывания (/O:-D
), что означает сначала самые новые элементы, for /F "eol=| delims="
, чтобы собрать и проанализировать вывод dir
по строкам, то есть файл по файлу, не за исключением имен файлов, начинающихся с ;
(eol=|
, |
является незаконным для имен файлов), а не для разбиения имен файлов, содержащих пробелы типа SPACE или TAB (delims=
); if
внутри цикла, чтобы проверить, достиг ли счетчик желаемого предельного числа, и в случае, если оно goto
; Вот связанный код :
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define global constants here:
set "TARGETPATH=\path\to\files\*.*"
set /A "TOTAL=10"
set /A "COUNT=0"
for /F "eol=| delims=" %%F in ('
dir /B /A:-D /T:C /O:-D "%TARGETPATH%"
') do (
echo(%%F
set /A COUNT+=1
setlocal EnableDelayedExpansion
if !COUNT! GEQ %TOTAL% (
endlocal
goto :NEXT
) else (
endlocal
)
)
:NEXT
endlocal
exit /B
Я переключил задержанное расширение переменной в цикле for /F
, чтобы избежать проблем, когда имена файлов файлов содержат восклицательные знаки !
, которые теряются в line echo(%%F
, если он включен.
Следующий код выполняет исходную задачу вашего вопроса, а именно: удалять файлы в заданном каталоге, но сохранять последнее число файлов:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define global constants here:
set "TARGETPATH=\path\to\files\*.*"
set /A "TOTAL=10"
set "SKIPOPT=" & if %TOTAL% GTR 0 set "SKIPOPT=skip=%TOTAL% "
for /F "%SKIPOPT%eol=| delims=" %%F in ('
dir /B /A:-D /T:C /O:-D "%TARGETPATH%"
') do (
del /P "%%F"
)
endlocal
exit /B
Поскольку for /F
поддерживает skip=
, чтобы пропустить указанное количество строк, и поэтому файлы в нашей ситуации, будем использовать его. Он указан косвенно здесь через переменную SKIPOPT
, которая содержит всю строку параметров, такую как skip=10
(при условии, что для параметра TOTAL
установлено значение 10
). Запрос if %TOTAL% GTR 0
реализован для того, чтобы сценарий не сработал, если TOTAL
- 0
, потому что for /F
не принимает параметр skip=0
.
Переключатель /P
на Команда del
позволяет отобразить подсказку Delete (Y/N)?
для целей тестирования. Если вам не нужны какие-либо подсказки, просто удалите его.