Java Android-使用后台服务导致应用程序崩溃

Java Android-使用后台服务导致应用程序崩溃,java,android,service,Java,Android,Service,我有一个在后台运行的应用程序,使用一个服务。主类启动服务,当用户停止主服务时,后台服务调用onDestroy函数并在后台启动服务。当我离开应用程序(在手机主页上)时,我遇到了一个问题,应用程序崩溃了,我不知道为什么。这部分代码的应用程序崩溃startService(newintent(this,LocationServices.class))。带着错误 java.lang.RuntimeException:无法停止服务LocationServices@1e605b2:java.lang.Ille

我有一个在后台运行的应用程序,使用一个服务。主类启动服务,当用户停止主服务时,后台服务调用onDestroy函数并在后台启动服务。当我离开应用程序(在手机主页上)时,我遇到了一个问题,应用程序崩溃了,我不知道为什么。这部分代码的应用程序崩溃
startService(newintent(this,LocationServices.class))。带着错误

java.lang.RuntimeException:无法停止服务LocationServices@1e605b2:java.lang.IllegalStateException:不允许启动服务意图{cmp=o/.LocationServices}:应用程序位于后台uid中

主要类别-

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this, LocationServices.class));
    }
}
服务级别-

public class LocationServices extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("LocationServices", "Service Start");
    return Service.START_STICKY_COMPATIBILITY;
}

@Override
public void onDestroy() {
    //super.onDestroy();
    startService(new Intent(this, LocationServices.class));
    Log.d("LocationServices", "Service End");
    }
}

为什么会发生这种情况?我如何修复它?

为什么要将此startService(新的Intent(this,LocationServices.class))添加到onDestroy中method@RejoylinLokeshwaran要在用户关闭主屏幕onDestroy()或onstop()中的appstart服务后再次启动服务,请从主类启动服务(new Intent(this,LocationServices.class));这一行放在mainactivity onDestroy()下,为什么要将此startService(new Intent(this,LocationServices.class))添加到onDestroy中method@RejoylinLokeshwaran在用户关闭主屏幕onDestroy()或onstop()中的appstart服务后再次启动服务@RejoylinLokeshwaran从主类startService(新意图(this,LocationServices.class))启动onDestroy();此行放在mainactivity onDestroy()下