应用程序销毁后,前台服务在某些手机中停止

时间:2019-05-10 12:51:13

标签: android foreground-service

应用程序销毁后,前台服务会在某些手机中停止,甚至要在应用程序已损坏的情况下运行前台服务。

清单:

<service android:name=".services.LocationService" />

这是我开始和停止服务的方式:

private void startLocationUpdates() {
    if (!isMyServiceRunning(LocationService.class)) {

        Intent locationServiceIntent = new Intent(this, LocationService.class);
        locationServiceIntent.putExtra(StringConstants.LOCATION_UPDATES, true);

        startService(locationServiceIntent);
    }
}

private void stopLocationUpdates() {
    Intent locationServiceIntent = new Intent(this, LocationService.class);
    locationServiceIntent.putExtra(StringConstants.LOCATION_UPDATES, false);

    startService(locationServiceIntent);
}

服务:

public class LocationService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "Service started");
    if (intent != null) {
      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(1, notification);

      } else {

        startService(new Intent(getApplicationContext(), MyForeGroundService.class));

    }
    }
    return START_STICKY;

} }

private NotificationCompat.Builder getNotificationBuilder(){
    return new NotificationCompat.Builder(this)
            .setContentIntent(MyApp.pendingIntent)
            .setContentText("setContentText")
            .setContentTitle(getString(R.string.app_name))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_black_24px))
            .setSmallIcon(R.drawable.ic_arrow_back_black_24px);
}

1 个答案:

答案 0 :(得分:0)

对于具有Oreo或更高版本操作系统的设备,运行服务有一定的限制,您必须为具有Oreo或更高版本的设备显示通知,您必须再做一件事,而不是startService()尝试使用{{1 }}有关更多信息,请查阅官方文档https://developer.android.com/about/versions/oreo/background