package com.android.mtp;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.Notification;
import android.app.Service;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.IBinder;
import android.os.Parcelable;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import com.android.internal.util.Preconditions;
import java.util.HashSet;
import java.util.Set;
public class MtpDocumentsService extends Service {
static final String ACTION_UPDATE_NOTIFICATION = "com.android.mtp.UPDATE_NOTIFICATION";
static final String EXTRA_DEVICE_IDS = "deviceIds";
static final String EXTRA_DEVICE_NOTIFICATIONS = "deviceNotifications";
private NotificationManager mNotificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = getSystemService(NotificationManager.class);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || ACTION_UPDATE_NOTIFICATION.equals(intent.getAction())) {
final int[] ids = intent.hasExtra(EXTRA_DEVICE_IDS) ?
intent.getExtras().getIntArray(EXTRA_DEVICE_IDS) : null;
final Notification[] notifications = intent.hasExtra(EXTRA_DEVICE_NOTIFICATIONS) ?
castToNotifications(intent.getExtras().getParcelableArray(
EXTRA_DEVICE_NOTIFICATIONS)) : null;
return updateForegroundState(ids, notifications) ? START_STICKY : START_NOT_STICKY;
}
return START_NOT_STICKY;
}
private boolean updateForegroundState(
@Nullable int[] ids, @Nullable Notification[] notifications) {
final Set<Integer> openedNotification = new HashSet<>();
final int size = ids != null ? ids.length : 0;
if (size != 0) {
Preconditions.checkArgument(ids != null);
Preconditions.checkArgument(notifications != null);
Preconditions.checkArgument(ids.length == notifications.length);
}
for (int i = 0; i < size; i++) {
if (i == 0) {
startForeground(ids[i], notifications[i]);
} else {
mNotificationManager.notify(ids[i], notifications[i]);
}
openedNotification.add(ids[i]);
}
final StatusBarNotification[] activeNotifications =
mNotificationManager.getActiveNotifications();
for (final StatusBarNotification notification : activeNotifications) {
if (!openedNotification.contains(notification.getId())) {
mNotificationManager.cancel(notification.getId());
}
}
if (size == 0) {
stopForeground(true );
stopSelf();
return false;
}
return true;
}
private static @NonNull Notification[] castToNotifications(@NonNull Parcelable[] src) {
Preconditions.checkNotNull(src);
final Notification[] notifications = new Notification[src.length];
for (int i = 0; i < src.length; i++) {
notifications[i] = (Notification) src[i];
}
return notifications;
}
}