Anonymous
ForegroundServiceIdnotStartIntimeException при использовании startForegroundService () с API FusedLocation [закрыто]
Сообщение
Anonymous » 18 июл 2025, 10:15
У меня есть одна проблема в службе переднего плана, и я не могу воспроизвести эту проблему, поэтому, если кто -то найдет аналогичную проблему, не могли бы вы помочь мне решить эту проблему.
Код: Выделить всё
**Fatal Exception: android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException
Context.startForegroundService() did not then call Service.startForeground():
ServiceRecord{91bb8e7 u0 com.londonserenitytherapist/.serviceandbroadcast.BookingTrackingForgroundService
c:com.londonserenitytherapist}
Caused by android.app.StackTrace
Last startServiceCommon() call for this service was made here**
< /code>
Ниже приведен моя служба переднего плана, которую я использовал для отправки местоположения на сервер для мониторинга местоположения: < /p>
public class BookingTrackingForgroundService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
apiHelper = new ApiHelper(getApplicationContext());
applicationContext = getApplicationContext();
detectBetteryLow();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
assert action != null;
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
Log.d("BookingService", "onStartCommand received action: " + action);
startTrackingForeground();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
}
}
return START_STICKY;
}
private void startTrackingForeground() {
Log.d("BookingService", "Starting foreground service setup...");
context = this;
startLocationUpdates();
Log.d("BookingService", "Location updates started.");
notify_interval1 = Prefs.with(this).readLong("notify_interval1", 5000);
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTaskToGetLocation(), 20000, notify_interval1);
mTimer.scheduleAtFixedRate(new TimerTaskToSendCsvFile(), 60000, 1800000); // Delay 1 min and period is 30 min
// mTimer.scheduleAtFixedRate(new TimerTaskToSendCsvFile(), 60000, 600000); // Delay 1 min and period is 10 min
prefsPrivate = getSharedPreferences(Constants.prefsKeys.PREFS_PRIVATE, Context.MODE_PRIVATE);
internet = new NetConnectionService(context);
Log.d("BookingService", "Timers scheduled.");
Intent notificationIntent = new Intent(this, ActTherapistDashboard.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Geolocation is running")
.setTicker("Geolocation").setSmallIcon(R.drawable.app_small_icon_white)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH) // High priority
.setOngoing(true) // Mark as ongoing
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); // Visible on lock screen
Notification notification = builder.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT; // Sticky notification
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setDescription(CHANNEL_DESCRIPTION);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
Log.d("BookingService", "Notification channel created.");
}
Log.d("BookingService", "Calling startForeground()");
startForeground(SERVICE_ID, notification);
Log.d("BookingService", "Foreground service started successfully.");
}
private void parsePushLatLong(String result) {
response = result;
insertIntoDb();
try {
JSONObject jobj = new JSONObject(result);
if (jobj.getString("FLAG").equalsIgnoreCase("true")) {
String IS_FIVE_FLAG = "" + jobj.optString("IS_FIVE_FLAG");
String IS_TRACKING_ON = "" + jobj.optString("IS_TRACKING_ON");
long TRACKING_TIME = jobj.optLong("TRACKING_TIME");
if (TRACKING_TIME != 0) {
delayTimeOneMin = TRACKING_TIME * intoMinute;
}
if (IS_TRACKING_ON.equalsIgnoreCase("1")) {
if (IS_FIVE_FLAG.equalsIgnoreCase("0")) {
if (notify_interval1 != delayTimeOneMin) {
if (isServiceRunningInForeground(context, BookingTrackingForgroundService.class)) {
try {
stopForegroundService();
notify_interval1 = delayTimeOneMin;
Prefs.with(BookingTrackingForgroundService.this).writeLong("notify_interval1", notify_interval1);
Intent intentService = new Intent(context, BookingTrackingForgroundService.class);
intentService.setAction(BookingTrackingForgroundService.ACTION_START_FOREGROUND_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if(isAppInForeground(context)) {
context.startForegroundService(intentService);
}
}
});
} else {
if(isAppInForeground(context)) {
context.startService(intentService);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (IS_FIVE_FLAG.equalsIgnoreCase("1")) {
if (notify_interval1 != delayTimeOneMin) {
if (isServiceRunningInForeground(context, BookingTrackingForgroundService.class)) {
try {
stopForegroundService();
notify_interval1 = delayTimeOneMin;
Prefs.with(BookingTrackingForgroundService.this).writeLong("notify_interval1", notify_interval1);
Intent intentService = new Intent(context, BookingTrackingForgroundService.class);
intentService.setAction(BookingTrackingForgroundService.ACTION_START_FOREGROUND_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if(isAppInForeground(context)) {
context.startForegroundService(intentService);
}
}
});
} else {
if(isAppInForeground(context)) {
context.startService(intentService);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} else {
SharedPreferences.Editor preEditor = prefsPrivate.edit();
preEditor.putString(Constants.prefsKeys.LOGIN_USER.OL_TRACKING_STATUS, "false");
preEditor.apply();
stopForegroundService();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Любая помощь или предложения будут высоко оценены.
Заранее!>
Подробнее здесь:
https://stackoverflow.com/questions/797 ... undservice
1752822943
Anonymous
У меня есть одна проблема в службе переднего плана, и я не могу воспроизвести эту проблему, поэтому, если кто -то найдет аналогичную проблему, не могли бы вы помочь мне решить эту проблему.[code]**Fatal Exception: android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{91bb8e7 u0 com.londonserenitytherapist/.serviceandbroadcast.BookingTrackingForgroundService c:com.londonserenitytherapist} Caused by android.app.StackTrace Last startServiceCommon() call for this service was made here** < /code> Ниже приведен моя служба переднего плана, которую я использовал для отправки местоположения на сервер для мониторинга местоположения: < /p> public class BookingTrackingForgroundService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); apiHelper = new ApiHelper(getApplicationContext()); applicationContext = getApplicationContext(); detectBetteryLow(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String action = intent.getAction(); assert action != null; switch (action) { case ACTION_START_FOREGROUND_SERVICE: Log.d("BookingService", "onStartCommand received action: " + action); startTrackingForeground(); break; case ACTION_STOP_FOREGROUND_SERVICE: stopForegroundService(); break; } } return START_STICKY; } private void startTrackingForeground() { Log.d("BookingService", "Starting foreground service setup..."); context = this; startLocationUpdates(); Log.d("BookingService", "Location updates started."); notify_interval1 = Prefs.with(this).readLong("notify_interval1", 5000); mTimer = new Timer(); mTimer.scheduleAtFixedRate(new TimerTaskToGetLocation(), 20000, notify_interval1); mTimer.scheduleAtFixedRate(new TimerTaskToSendCsvFile(), 60000, 1800000); // Delay 1 min and period is 30 min // mTimer.scheduleAtFixedRate(new TimerTaskToSendCsvFile(), 60000, 600000); // Delay 1 min and period is 10 min prefsPrivate = getSharedPreferences(Constants.prefsKeys.PREFS_PRIVATE, Context.MODE_PRIVATE); internet = new NetConnectionService(context); Log.d("BookingService", "Timers scheduled."); Intent notificationIntent = new Intent(this, ActTherapistDashboard.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(getString(R.string.app_name)) .setContentText("Geolocation is running") .setTicker("Geolocation").setSmallIcon(R.drawable.app_small_icon_white) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) // High priority .setOngoing(true) // Mark as ongoing .setCategory(NotificationCompat.CATEGORY_SERVICE) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); // Visible on lock screen Notification notification = builder.build(); notification.flags |= Notification.FLAG_ONGOING_EVENT; // Sticky notification if (Build.VERSION.SDK_INT >= 26) { NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); channel.setDescription(CHANNEL_DESCRIPTION); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); Log.d("BookingService", "Notification channel created."); } Log.d("BookingService", "Calling startForeground()"); startForeground(SERVICE_ID, notification); Log.d("BookingService", "Foreground service started successfully."); } private void parsePushLatLong(String result) { response = result; insertIntoDb(); try { JSONObject jobj = new JSONObject(result); if (jobj.getString("FLAG").equalsIgnoreCase("true")) { String IS_FIVE_FLAG = "" + jobj.optString("IS_FIVE_FLAG"); String IS_TRACKING_ON = "" + jobj.optString("IS_TRACKING_ON"); long TRACKING_TIME = jobj.optLong("TRACKING_TIME"); if (TRACKING_TIME != 0) { delayTimeOneMin = TRACKING_TIME * intoMinute; } if (IS_TRACKING_ON.equalsIgnoreCase("1")) { if (IS_FIVE_FLAG.equalsIgnoreCase("0")) { if (notify_interval1 != delayTimeOneMin) { if (isServiceRunningInForeground(context, BookingTrackingForgroundService.class)) { try { stopForegroundService(); notify_interval1 = delayTimeOneMin; Prefs.with(BookingTrackingForgroundService.this).writeLong("notify_interval1", notify_interval1); Intent intentService = new Intent(context, BookingTrackingForgroundService.class); intentService.setAction(BookingTrackingForgroundService.ACTION_START_FOREGROUND_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if(isAppInForeground(context)) { context.startForegroundService(intentService); } } }); } else { if(isAppInForeground(context)) { context.startService(intentService); } } } catch (Exception e) { e.printStackTrace(); } } } } else if (IS_FIVE_FLAG.equalsIgnoreCase("1")) { if (notify_interval1 != delayTimeOneMin) { if (isServiceRunningInForeground(context, BookingTrackingForgroundService.class)) { try { stopForegroundService(); notify_interval1 = delayTimeOneMin; Prefs.with(BookingTrackingForgroundService.this).writeLong("notify_interval1", notify_interval1); Intent intentService = new Intent(context, BookingTrackingForgroundService.class); intentService.setAction(BookingTrackingForgroundService.ACTION_START_FOREGROUND_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if(isAppInForeground(context)) { context.startForegroundService(intentService); } } }); } else { if(isAppInForeground(context)) { context.startService(intentService); } } } catch (Exception e) { e.printStackTrace(); } } } } } else { SharedPreferences.Editor preEditor = prefsPrivate.edit(); preEditor.putString(Constants.prefsKeys.LOGIN_USER.OL_TRACKING_STATUS, "false"); preEditor.apply(); stopForegroundService(); } } else { } } catch (JSONException e) { e.printStackTrace(); } } } [/code] Любая помощь или предложения будут высоко оценены. Заранее!> Подробнее здесь: [url]https://stackoverflow.com/questions/79704352/foregroundservicedidnotstartintimeexception-when-using-startforegroundservice[/url]