Можно ли запустить службу из фоновой службы?
Это работает только тогда, когда приложение открыто...
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-уведомление.




Воспользуйтесь этой услугой:
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" />