Tính năng này không còn hoạt động với Android 7.1 và có thể vi phạm chính sách dành cho nhà phát triển của Google Play .
Thay vào đó, hãy yêu cầu người dùng chặn thông báo dịch vụ .
Đây là cách tôi thực hiện kỹ thuật trong câu trả lời của Lior Iluz .
Mã
ForegroundService.java
public class ForegroundService extends Service {
    static ForegroundService instance;
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        if (startService(new Intent(this, ForegroundEnablingService.class)) == null)
            throw new RuntimeException("Couldn't find " + ForegroundEnablingService.class.getSimpleName());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = null;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
ForegroundEnablingService.java
public class ForegroundEnablingService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (ForegroundService.instance == null)
            throw new RuntimeException(ForegroundService.class.getSimpleName() + " not running");
        
        startForeground(ForegroundService.instance);
        startForeground(this);
        
        stopForeground(true);
        
        
        stopSelf();
        return START_NOT_STICKY;
    }
    private static final int NOTIFICATION_ID = 10;
    private static void startForeground(Service service) {
        Notification notification = new Notification.Builder(service).getNotification();
        service.startForeground(NOTIFICATION_ID, notification);
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
AndroidManifest.xml
<service android:name=".ForegroundEnablingService" />
<service android:name=".ForegroundService" />
Khả năng tương thích
Đã thử nghiệm và làm việc trên:
- Trình giả lập chính thức
- 4.0.2
- 4.1.2
- 4.2.2
- 4.3.1
- 4.4.2
- 5.0.2
- 5.1.1
- 6.0
- 7.0
 
- Sony Xperia M
- Samsung Galaxy?
- Genymotion
- CyanogenMod
Không còn hoạt động với Android 7.1.