0

我想我的應用程序能夠從這個字符串數組隨機選擇一個項目:Android的:把從字符串數組隨機項,以通知

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

而且在發送通知的項目關閉的用戶。 (將在用戶選擇的時間,使用警報管理器)

我相信我可以使用以下方法生成一個隨機項目。 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

+0

在什麼特定的時間你卡住了?你有什麼問題?你讀過android通知文檔嗎? – vidstige

回答

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