Ошибка службы Android: android.app.ForegroundServiceDidNotStartInTimeExceptionAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Ошибка службы Android: android.app.ForegroundServiceDidNotStartInTimeException

Сообщение Anonymous »

Я хочу создать службу в Android, чтобы начать длительное действие, но происходит сбой с отображением следующего сообщения:

android.app.ForegroundServiceDidNotStartInTimeException: Context .startForegroundService() тогда не вызывал Service.startForeground(): ServiceRecord{2134ac4 u0 com.example.foregroundservice/.MyForegroundService}
> at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:1923)

в android.app.ActivityThread.access$2700(ActivityThread.java:247)

в android.app .ActivityThread$H.handleMessage(ActivityThread.java:2148)

at android.os.Handler.dispatchMessage(Handler.java:106)

в android.os.Looper.loopOnce(Looper.java:201)

в android.os. Looper.loop(Looper.java:288)

at android.app.ActivityThread.main(ActivityThread.java:7839)

в java.lang.reflect.Method.invoke(собственный метод)

в com.android.internal .os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

Вот моя основная активность:

Код: Выделить всё

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (!foregroundServiceRunning())
{
Intent serviceIntent = new Intent(this, MyForegroundService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
}
}

}

public void getTimeButtonPressed(View v)
{
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(MyForegroundService.getsystemtime());
}

public boolean foregroundServiceRunning()
{
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service: activityManager.getRunningServices(Integer.MAX_VALUE))
{
if(MyForegroundService.class.getName().equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
И это служба переднего плана

Код: Выделить всё

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new Thread(
new Runnable()
{
@Override
public void run()
{
while (true)
{
Log.e("Service", "Service is running...");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

}
}
}

).start();

final String CHANNELID ="Foreground Service ID";
NotificationChannel channel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
channel = new NotificationChannel(CHANNELID, CHANNELID, NotificationManager.IMPORTANCE_LOW);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
getSystemService(NotificationManager.class).createNotificationChannel(channel);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notification = new Notification.Builder(this, CHANNELID)
.setContentText("Service is running...")
.setContentTitle("Service enabled")
.setSmallIcon(R.drawable.ic_launcher_background);
}
startForeground(1001, notification.build());
return super.onStartCommand(intent, flags, startId);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

public static String getsystemtime()
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ss:mm:hh dd/MM/yyyy", Locale.US);
return simpleDateFormat.format(new Date());
}
Что мне делать, чтобы устранить проблему?
Изменить
Я добавляю новую строку в onStartCommand. Происходит странная вещь: на моем эмуляторе он работает без проблем, но при запуске на моем телефоне (Redmi 10) он сразу же вылетает со следующими сообщениями:
сообщение об ошибке1
Сообщение об ошибке2

Подробнее здесь: https://stackoverflow.com/questions/781 ... eexception
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»