Search code examples
androidperformanceandroid-workmanager

Android Work manager get triggered everytime I open my app


I have made a periodic work manager and its misbehaving heavily. Instead of doing a work in the set interval it executes it every minute. And it also gets triggered everytime i open the app. This means if I open my app 50 times in a minute , It does the work 50 times. Here is my code

public class UpdateUserDataService extends Worker {
    public UpdateUserDataService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @NonNull
    @Override
    public Result doWork() {
        FirebaseMessaging.getInstance().getToken().addOnSuccessListener(s -> {
            DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Update");
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy_h:mm a", Locale.getDefault());
            Calendar c = Calendar.getInstance();
            String currentDate = dateFormat.format(c.getTime());
            JobFooter jobFooter = new JobFooter(currentDate, s);
            reference.child(dateFormat.format(new Date())).setValue(jobFooter);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
            notificationIntent.putExtra("Notification", true);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationHelper notificationHelper = new NotificationHelper(getApplicationContext(), defaultSoundUri);
            Notification.Builder notificationBuilder = notificationHelper.getNotification("Title", currentDate, intent);
            notificationHelper.notify(10, notificationBuilder);
        });
        return Result.success();
    }
}

And in my main activity under oncreate method

 Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresBatteryNotLow(true)
                .build();
        PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(
                UpdateUserDataService.class, 15, TimeUnit.MINUTES)
                .setConstraints(constraints)
                .build();

        WorkManager.getInstance(this).enqueue(periodicWorkRequest);

All I want is my code to execute after every 15 minutes followings OS norms and constraints and irrespective of my app getting opened or not.


Solution

  • String EXPIRY_CHECK = "unique_worker_name";
    
     Constraints constraints = new Constraints.Builder()
                .setRequiresBatteryNotLow(true)
                .build();
                
    PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest
          .Builder(UpdateUserDataService.class, 1, TimeUnit.DAYS)
          .setConstraints(constraints).build();
                
    WorkManager.getInstance(this)
          .enqueueUniquePeriodicWork(EXPIRY_CHECK, ExistingPeriodicWorkPolicy.KEEP, periodicWorkRequest);
    

    This will check if an already existing worker is initialised or not and will not launch a new worker if it is already running.