Search code examples
androidandroid-notificationsandroid-workmanager

How can I send random notifications via Workmanager periodically


I am able to send periodically notifications in every 15 minutes but I couldn't change the content of notification. I have a string-array and workmanager sends always the same item. For example at first it takes the valur "four" and it sends always "four"

1 - I defined a string array in strings.xml

<string-array name="numbers">
    <item>one</item>
    <item>two</item>
    <item>three</item>
    <item>four</item>
    <item>five</item>
</string-array>

2 - My MainActivity Class

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String KEY_TASK_DESC = "key_task_desc";


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

    String[] list = getResources().getStringArray(R.array.numbers);

    Random random = new Random();
    int number = random.nextInt(list.length);

    Data data = new Data.Builder()
            .putString(KEY_TASK_DESC, list[number]).build();

    PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest
            .Builder(MyWorker.class, 15, TimeUnit.MINUTE)
            .setInputData(data)
            .build();

    WorkManager.getInstance().enqueue(periodicWorkRequest);

}}

3 - MyWorker Class containing displayNotif(String inputData) method

public class MyWorker extends Worker {

public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {

    String inputData = getInputData().getString(MainActivity.KEY_TASK_DESC);
    displayNotif(inputData);

    return Result.success();
}

private void displayNotif(String inputData) {
    NotificationManager manager =
            (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel channel = new NotificationChannel("notif",
                "notif", NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "notif")
            .setContentText(inputData)
            .setSmallIcon(R.mipmap.ic_launcher);

    manager.notify(1, builder.build());
}}

Solution

  • I think you're perhaps misunderstanding your PeriodicWorkRequest setup.

    You are only calling setInputData once, with one data (your string). Every time it runs, it still only has this data.

    To randomly display a string, your random selection has to happen inside your Worker's doWork.