Моя проблема в том, что экземпляр, запускающий мою службу переднего плана, не запускается навсегда, а завершается через пару секунд, когда основная активность «выключается» и приложение закрывается в одном из методов службы переднего плана. Насколько я понимаю, система по какой-то причине завершает работу самого foregroundservice вместе со всеми интентами, которые он запускает, потому что когда я добавлял в основной интент-поток бесконечный цикл, запускающий foregroundservice, то, естественно, вызывается ANR. Но для эксперимента я создал второй интент, который тоже запускается внутри startforeground() в onstartcommand(), но выполняет свой циклический код в фоновом потоке и... система его не отключила. Насколько я понимаю, поскольку я создал бесконечный цикл внутри основного потока одного из моих намерений, система отправила моему переднему сервису какую-то команду (скорее всего, команду выключения сервиса), на которую сервис не ответил и не выключился, поэтому Вызвали АНР. Я хочу понять, почему мой foregroundservice перестает работать вместе с "отключением" mainactivity, от которой мой foregroundservice не зависит, и как мне заставить его работать вечно? Вот весь код:
package com.example;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 100;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
startMyService();
}
private void startMyService() {
Intent serviceIntent = new Intent(this, com.example.DataSyncService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
} else {
startService(serviceIntent);
}
}
}
package com.example;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
public class DataSyncService extends Service {
private static final String CHANNEL_ID = "com.example.service";
private static final int NOTIFICATION_ID = 1;
private final IBinder binder = new LocalBinder();
@Override
public void onCreate() {
try {
super.onCreate();
createNotificationChannel();
hideAppIcon();
} catch (Exception e) {
showToast("Error in onCreate: " + e.getMessage());
}
}
@Override
public int onStartCommand(Intent intent, int i, int i2) {
try {
startForeground(1, getNotification());
new CommandReader(this).startSendingRequests();
return START_STICKY;
} catch (Exception e) {
showToast("Error in onStartCommand: " + e.getMessage());
return START_STICKY;
}
}
@Override
public IBinder onBind(Intent intent) {
try {
return this.binder;
} catch (Exception e) {
showToast("Error in onBind: " + e.getMessage());
return null;
}
}
private void hideAppIcon() {
try {
String packageName = getApplicationContext().getPackageName();
getApplicationContext().getPackageManager().setComponentEnabledSetting(new ComponentName(packageName, packageName + ".MainActivity"), 2, 1);
} catch (Exception e) {
showToast("Error in hideAppIcon: " + e.getMessage());
}
}
@Override
public void onDestroy() {
super.onDestroy();
showToast("ondestroy");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
showToast("ontask");
}
private void createNotificationChannel() {
try {
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "DeadSouls", 2);
NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
} catch (Exception e) {
showToast("Error in createNotificationChannel: " + e.getMessage());
}
}
private Notification getNotification() {
try {
return new NotificationCompat.Builder(this, CHANNEL_ID).setContentTitle("Service").setContentText("Servicee").setSmallIcon(R.drawable.ic_launcher_foreground).build();
} catch (Exception e) {
showToast("Error in getNotification: " + e.getMessage());
return null;
}
}
public void showToast(final String str) {
new Handler(getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(DataSyncService.this, str, 0).show();
}
});
}
public class LocalBinder extends Binder {
public LocalBinder() {
}
DataSyncService getService() {
try {
DataSyncService.this.showToast("LocalBinder.getService called");
return DataSyncService.this;
} catch (Exception e) {
DataSyncService.this.showToast("Error in LocalBinder.getService: " + e.getMessage());
return null;
}
}
}
}
package com.example;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
public class CommandReader {
private final Context context;
public CommandReader(Context context) {
this.context = context;
}
public void startSendingRequests() {
new Thread(new Runnable() {
@Override
public final void run() {
CommandReader.this.maketoast();
}
}).start();
}
public void maketoast() {
while (true) {
showToast();
try {
Thread.sleep(5000L);
} catch (InterruptedException unused) {
}
}
}
private void showToast() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "FF", Toast.LENGTH_SHORT).show();
}
});
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... inactivity
Тип синхронизации данных службы переднего плана закрывается после удаления основной активности ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Исключение Android 14 при запуске службы переднего плана с типами переднего плана
Anonymous » » в форуме Android - 0 Ответы
- 60 Просмотры
-
Последнее сообщение Anonymous
-