vendredi 15 octobre 2021

java, how to generate a good random int

android app, it needs to generate a random int key for different use cases. it has a function for the random int, which is fine in most time, but in the case if it is called frequently it may return a same number.

    int nextRandomId() {
        return (int) SystemClock.uptimeMillis();
    }

one of the case when build the notification action buttons, there will be multiple action button each will have its own pendingIntent with requestid from nextRandomId().


Intent broadcastIntent_one = Intent(this, NotificationReceiver.class);
broadcastIntent_one.putExtra("action", ACTION_ONE);  //ACTION_TWO, ACTION_THREE
broadcastIntent_one.putExtra(EXTRA_NOTIFICATION_ID, notificationId)

// adding action for broadcast
   PendingIntent broadcastPendingIntent_one =
      PendingIntent.getBroadcast(application, nextRandomId(), broadcastIntent_one, PendingIntent.FLAG_UPDATE_CURRENT);

... ...
 builder.addAction(null, "action one", broadcastPendingIntent_one);
 builder.addAction(null, "action two", broadcastPendingIntent_two);
 builder.addAction(null, "action three", broadcastPendingIntent_three);


in case of building three action buttons, the log shows some of the random numbers are same:

16:00:55.003  nextRandomId(): 400267105
16:00:55.003  nextRandomId(): 400267106
16:00:55.003  nextRandomId(): 400267106

so in the NotificationReceiver the last two action buttons are all having the ACTION_THREEin the extra.

what is a better way to generate a number not duplicate (no clash, efficient)?




Aucun commentaire:

Enregistrer un commentaire