你的问题是由于使用了有界前台服务所导致的。请参考:https://developer.android.com/guide/components/bound-services
有界服务通常只在为其他应用程序组件提供服务时才存在,并且不会无限期地在后台运行。
基本上,你的服务存在取决于是否已绑定。
另一种选择是不使用Bind方法,而是使用Context.startService()或Context.startForegroundService()来启动服务并让它永久运行。就像这样:
Intent intent = new Intent(getApplicationContext(), ForegroundService.class);
intent.setAction(ForegroundService.ACTION_START_FOREGROUND_SERVICE);
startService(intent);
ForegroundService类看起来像这样:
public class ForegroundService extends Service {
private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";
public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
public ForegroundService () {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG_FOREGROUND_SERVICE, "My foreground service onCreate().");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null)
{
String action = intent.getAction();
switch (action)
{
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
private void startForegroundService()
{
Notification notification = builder.build();
startForeground(1, notification);
}
private void stopForegroundService()
{
stopForeground(true);
stopSelf();
}
}
在这种情况下,您不需要同步服务状态,因为它将尽可能地保持活动状态,并且只有在调用stopSelf()时才会停止。即使应用程序进入后台,服务也不会停止。
另外,您可以使用Broadcast result、livedata或EventBus方法在服务和活动之间进行同步/通信。
希望这个回答能够帮到您。如果这不是您想要的,请谅解,这只是一个想法。