Created
December 4, 2026 07:22
-
-
Save sunmeat/33d6709016d6a4c7fc30f30316b137e5 to your computer and use it in GitHub Desktop.
сервіс без іконки сповіщення в статус барі
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| MainActivity.java: | |
| package site.sunmeat.services; | |
| import android.content.Intent; | |
| import android.os.Bundle; | |
| import android.view.View; | |
| import android.widget.Toast; | |
| import androidx.appcompat.app.AppCompatActivity; | |
| import androidx.core.content.ContextCompat; | |
| public class MainActivity extends AppCompatActivity { | |
| @Override | |
| public void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| setContentView(R.layout.activity_main); | |
| // дозвіл POST_NOTIFICATIONS не запитуємо | |
| } | |
| public void start(View v) { | |
| Intent intent = new Intent(this, MyService.class); | |
| ContextCompat.startForegroundService(this, intent); | |
| Toast.makeText( | |
| this, | |
| "Запит на запуск сервісу", | |
| Toast.LENGTH_SHORT | |
| ).show(); | |
| } | |
| public void stop(View v) { | |
| Intent intent = new Intent(this, MyService.class); | |
| boolean stopped = stopService(intent); | |
| Toast.makeText( | |
| this, | |
| stopped ? "Сервіс зупинено" : "Сервіс не запущено", | |
| Toast.LENGTH_SHORT | |
| ).show(); | |
| } | |
| } | |
| ================================================================================================================== | |
| MyService.java: | |
| package site.sunmeat.services; | |
| import android.app.Notification; | |
| import android.app.NotificationChannel; | |
| import android.app.NotificationManager; | |
| import android.app.Service; | |
| import android.content.Intent; | |
| import android.os.Handler; | |
| import android.os.IBinder; | |
| import android.os.Looper; | |
| import android.util.Log; | |
| import androidx.core.app.NotificationCompat; | |
| public class MyService extends Service { | |
| private static final String CHANNEL_ID = "alex_service"; | |
| private static final int NOTIFICATION_ID = 101; | |
| private Handler handler; | |
| private Runnable runnable; | |
| private int counter = 0; | |
| private boolean isRunning = false; | |
| @Override | |
| public IBinder onBind(Intent intent) { | |
| return null; | |
| } | |
| @Override | |
| public void onCreate() { | |
| super.onCreate(); | |
| // канал сповіщень все одно треба | |
| createNotificationChannel(); | |
| handler = new Handler(Looper.getMainLooper()); | |
| runnable = new Runnable() { | |
| @Override | |
| public void run() { | |
| counter++; | |
| Log.d("notification_test", "Counter: " + counter); | |
| // тут якась логіка сервісу | |
| handler.postDelayed(this, 1000); | |
| } | |
| }; | |
| } | |
| @Override | |
| public int onStartCommand(Intent intent, int flags, int startId) { | |
| if (!isRunning) { | |
| // переводимо сервіс у режим Foreground | |
| startForeground(NOTIFICATION_ID, createNotification()); | |
| isRunning = true; | |
| handler.post(runnable); | |
| Log.d("notification_test", "Сервіс запущено"); | |
| } | |
| // дозволяємо системі відновити сервіс після завершення процесу | |
| return START_STICKY; | |
| } | |
| private Notification createNotification() { | |
| // сповіщення є обов'язковим для Foreground Service, | |
| // навіть якщо застосунок не має дозволу POST_NOTIFICATIONS | |
| return new NotificationCompat.Builder(this, CHANNEL_ID) | |
| .setContentTitle("Foreground Service") | |
| .setContentText("Сервіс працює") | |
| .setSmallIcon(android.R.drawable.ic_dialog_info) | |
| .setSilent(true) | |
| .setOngoing(true) | |
| .setOnlyAlertOnce(true) | |
| .setPriority(NotificationCompat.PRIORITY_LOW) | |
| .build(); | |
| } | |
| private void createNotificationChannel() { | |
| var channel = new NotificationChannel( | |
| CHANNEL_ID, | |
| "Foreground Service", | |
| NotificationManager.IMPORTANCE_LOW | |
| ); | |
| channel.setDescription("Канал фонового сервісу"); | |
| channel.setSound(null, null); | |
| channel.enableVibration(false); | |
| channel.setShowBadge(false); | |
| NotificationManager manager = getSystemService(NotificationManager.class); | |
| manager.createNotificationChannel(channel); | |
| } | |
| @Override | |
| public void onDestroy() { | |
| handler.removeCallbacks(runnable); | |
| isRunning = false; | |
| // видаляємо сповіщення та виходимо з режиму Foreground | |
| stopForeground(STOP_FOREGROUND_REMOVE); | |
| Log.d("notification_test", "Сервіс зупинено"); | |
| super.onDestroy(); | |
| } | |
| } | |
| ================================================================================================================== | |
| AndroidManifest.xml: | |
| <manifest xmlns:android="http://schemas.android.com/apk/res/android" | |
| xmlns:tools="http://schemas.android.com/tools"> | |
| <!-- !!! --> | |
| <uses-permission | |
| android:name="android.permission.FOREGROUND_SERVICE" /> | |
| <!-- !!! --> | |
| <uses-permission | |
| android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" /> | |
| <!-- видаляємо дозвіл на сповіщення, | |
| навіть якщо його додає стороння бібліотека --> | |
| <uses-permission | |
| android:name="android.permission.POST_NOTIFICATIONS" | |
| tools:node="remove" /> | |
| <application> | |
| <!-- реєстрація фонового сервісу --> | |
| <service | |
| android:name=".MyService" | |
| android:enabled="true" | |
| android:exported="false" | |
| android:stopWithTask="false" | |
| android:foregroundServiceType="specialUse"> | |
| <!-- опис призначення сервісу !!! --> | |
| <property | |
| android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" | |
| android:value="foreground service counter demonstration" /> | |
| </service> | |
| <activity | |
| android:name=".MainActivity" | |
| android:exported="true"> | |
| <intent-filter> | |
| <action android:name="android.intent.action.MAIN" /> | |
| <category android:name="android.intent.category.LAUNCHER" /> | |
| </intent-filter> | |
| </activity> | |
| </application> | |
| </manifest> | |
| ================================================================================================================== | |
| даний підхід має спрацювати локально, але при публікації треба буде заповнити окрему декларацію. | |
| згідно з офіційною політикою Google Play, використання Foreground Service повинно відповідати таким критеріям: | |
| 1) Play Console Help - Користь для користувача | |
| Сервіс забезпечує функціональність, яка безпосередньо пов'язана з основним призначенням застосунку. | |
| 2) Усвідомлений запуск | |
| Користувач самостійно запускає відповідну функцію або усвідомлює, що вона працює. | |
| 3) Можливість зупинки | |
| Користувач повинен мати можливість припинити роботу сервісу. | |
| 4) Необхідність негайного виконання | |
| Відкладення або переривання операції повинно негативно впливати на функціональність застосунку чи досвід користувача. | |
| 5) Обмежена тривалість роботи | |
| Сервіс працює лише протягом часу, необхідного для виконання відповідного завдання. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment