应用程序销毁后,前台服务会在某些手机中停止,甚至要在应用程序已损坏的情况下运行前台服务。
<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);
}
答案 0 :(得分:0)
对于具有Oreo或更高版本操作系统的设备,运行服务有一定的限制,您必须为具有Oreo或更高版本的设备显示通知,您必须再做一件事,而不是startService()
尝试使用{{1 }}有关更多信息,请查阅官方文档https://developer.android.com/about/versions/oreo/background