Android:将随机项目从字符串数组放入通知中 [英] Android: Placing a random item from a String Array in to Notifications

查看:97
本文介绍了Android:将随机项目从字符串数组放入通知中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

并在通知中将项目发送给用户. (将在用户使用Alarmmanager选择的时间)

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

我相信我可以使用以下方法生成随机项目. 如何从android中的字符串数组?

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?

非常感谢,

-迈克

推荐答案

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

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

然后使用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);

这篇关于Android:将随机项目从字符串数组放入通知中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆