1

I want to create a Service in Android to start a long activity but it crashes with the following message shown:

android.app.ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{2134ac4 u0 com.example.foregroundservice/.MyForegroundService} > at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:1923)
at android.app.ActivityThread.access$2700(ActivityThread.java:247)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2148)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

Here is my MainActivity:

@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;
}

And it is the foreground service

@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());
}

What I shall I do to fix the problem?

Edit

I add a new line to the onStartCommand. A strange thing happens: it runs smoothly on my emulator but it crashes immediately when running on my phone (redmi 10) with the following messages shown:

error message1

error message2

1
  • Post the stack trace as code in the question rather than a link to a url. Commented Mar 11, 2024 at 11:39

2 Answers 2

0

In your Service.onStartCommand() you create a Notification, but you never use it. You need to call startForeground() and pass your Notification. If the Activity calls startForegroundService() then Android expects that the Service will call startForeground() inside onStartCommand().

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your suggestion. I add one more line to the onStartCommand. It runs smoothly on emmulator but it crashes immediately on my phone. What shall I do?
You need to declare the foreground service type in your manifest. See developer.android.com/about/versions/14/changes/…
0

Android 14 requires that foreground services are given a service type. The error message in the links are pointing out that you haven't declared one.

You can find more information baout that here : https://developer.android.com/about/versions/14/changes/fgs-types-required

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.