Android: Placing a random item from a String Array

2019-09-11 07:36发布

I want my app to be able to pick a random item from this string array:

<string-array name="quote_list">
    <item>Quote 1 </item>
    <item>Quote 2 </item>
    <item>Quote 3</item> </string-array>

And send the item off in a notification to the user. (Will be at a time chosen by user, using alarmmanager)

I believe I can generate a random item using the following method. How to get a random value from a string array in android?

Would I start off with something like this?

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText(String randomStr);

I still don't know really how I would go about placing a random item into a notification. Is it also possible to make it so the items the app chooses do not repeat?

Many Thanks,

-Mike

1条回答
你好瞎i
2楼-- · 2019-09-11 08:03

First get the random value from the string array (like the link you mentioned):

String[] array = context.getResources().getStringArray(R.array.animals_array);
String randomStr = array[new Random().nextInt(array.length)];

Then use NotificationManager to show randomStr to user:

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

int icon = R.drawable.icon4;        
CharSequence tickerText = "ticker-text";  
long when = System.currentTimeMillis();         
Context context = getApplicationContext();     
CharSequence contentTitle = "MyTitle";  
CharSequence contentText = randomStr;      
Intent notificationIntent = new Intent(this, Example.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
查看更多
登录 后发表回答