Android: Placing a random item from a String Array in to Notifications

混江龙づ霸主 提交于 2019-12-12 03:58:21

问题


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:


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);


来源:https://stackoverflow.com/questions/27664823/android-placing-a-random-item-from-a-string-array-in-to-notifications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!