Запустить службу в фоновом режиме

Можно ли запустить службу из фоновой службы?

Это работает только тогда, когда приложение открыто...

Intent service = new Intent(this, MyForegroundSerivce.class);
service.setAction(Constants.ACTION.START_ACTION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   startForegroundService(service);
} else {
   startService(service);
}

Я действительно не запускаю службу, я только вызываю ее с действием, чтобы что-то запустить, когда приходит push-уведомление.

Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
0
0
524
1

Ответы 1

Воспользуйтесь этой услугой:

Start Service

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     ContextCompat.startForegroundService(MainActivity.this, new Intent(MainActivity.this, ServiceBG.class));
 } else {
     startService(new Intent(MainActivity.this, ServiceBG.class));
 }

Service Class

public class ServiceBG extends Service {

    private static final String NOTIFICATION_CHANNEL_ID = "my_notification";
    private static final long TIME_INTERVAL = 10000;

    private Handler handlerThred;
    private Context mContext;


    @Override
    public void onCreate() {
        super.onCreate();


        mContext = this;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setOngoing(false)
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(getResources().getColor(R.color.white))
                .setPriority(Notification.PRIORITY_MIN);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
            notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID);
            notificationChannel.setSound(null, null);
            notificationManager.createNotificationChannel(notificationChannel);
            startForeground(1, builder.build());
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.w("Service", "BGS > Started");

        if (handlerThred == null) {
            handlerThred = new Handler();
            handlerThred.post(runnableThred);
            Log.w("Service ", "BGS > handlerThred Initialized");
        } else {
            Log.w("Service ", "BGS > handlerThred Already Initialized");
        }

        return START_STICKY;
    }

    private Runnable runnableThred = new Runnable() {

        @Override
        public void run() {

            Log.w("Service ", "BGS >> Running");

            if (handlerSendLocation != null && runnableThred != null)
                handlerSendLocation.postDelayed(runnableThred, TIME_INTERVAL);
        }
    };

    @Override
    public void onDestroy() {


        Log.w("Service", "BGS > Stopped");

        stopSelf();
        super.onDestroy();
    }

}

AndroidManifest.XML

 <service
            android:name = ".ServiceBG"
            android:enabled = "true"
            android:exported = "true" />

Другие вопросы по теме