Android:将字符串数组中的随机项放入通知中

时间:2014-12-27 05:57:01

标签: android arrays alarmmanager android-notifications notificationmanager

我希望我的应用能够从此字符串数组中选择一个随机项:

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

并在通知中将该项目发送给用户。 (将在用户选择的时间,使用alarmmanager)

我相信我可以使用以下方法生成随机项目。 How to get a random value from a string array in android?

我会从这样的事情开始吗?

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

我仍然不知道如何将随机项目放入通知中。是否也可以使应用程序选择的项目不重复?

非常感谢,

-Mike

1 个答案:

答案 0 :(得分:0)

首先从字符串数组中获取随机值(如您提到的链接):

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

然后使用NotificationManager向用户显示randomStr

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