0

I'm using Android WorkManager API. And here is the requirement: When a Worker finish the background work, if the app is in foreground, it will not send a notification. Otherwise, it will send a notification.

I tried the code from here to check if an activity is active before sending notification. But it doesn't work.

public class MyWorker extends Worker {
    public Result doWork() {
        if (!isActivityForeground(MainActivity.class)) {
            // send notification
        }
        return Result.success();
    }

    private boolean isActivityForeground(Class activityClass) {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
        return activityClass.getName().equals(tasks.get(0).getTaskInfo().topActivity.getClassName());
    }
}

When I remove if, a notification was sent.

wannik
  • 12,212
  • 11
  • 46
  • 58

0 Answers0