我有一个使用服务在后台运行的应用。主类启动服务,当用户停止主服务时,后台服务调用onDestroy函数并在后台重新启动服务。当我离开应用程序(在手机的主页上)应用程序崩溃时,我遇到了问题,我不知道为什么。应用程序在Service类的代码startService(new Intent(this, LocationServices.class));
的这部分上崩溃。错误
java.lang.RuntimeException:无法停止服务LocationServices @ 1e605b2:java.lang.IllegalStateException:不允许启动服务Intent {cmp = o / .LocationServices}:app在后台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");
}
}
为什么会发生这种情况,我该如何解决?