2012-07-22 102 views
1

我有一個服務在後臺運行,我想通知用戶,如果有新的數據,我已經使用通知管理器,並且出現通知,但是當它點擊它時,它不會'採取任何動作(這是爲了顯示活動 我在Android的新的和這裏是我的代碼使用NotificationManager到Android服務

NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     Notification notification = new Notification(R.drawable.shoppingcarticon, 
       "Nouvelle notification de ShopAlert", System.currentTimeMillis()); 
     notification.defaults |= Notification.DEFAULT_VIBRATE; 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     Intent intent = new Intent(this,GooglemapActivity.class); 
     PendingIntent activity = PendingIntent.getService(this, 0, intent, 0); 
     notification.setLatestEventInfo(this, "This is the title", 
       "This is the text", activity); 
     notification.number += 1; 
     notificationmanager.notify(0, notification); 

您的幫助將不勝感激

回答

4

您可以使用此代碼。根據需要將Main.Class更改爲您的活動類,標題和內容文本。

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


        int icon = R.drawable.ic_action_search; 
        CharSequence tickerText = "Pet Parrot"; 
        long when = System.currentTimeMillis(); 

        Notification notification = new Notification(icon, 
          tickerText, when); 
        notification.flags |= Notification.FLAG_AUTO_CANCEL; 
        Context context = getApplicationContext(); 
        CharSequence contentTitle = "Hungry!"; 
        CharSequence contentText = "your parrot food meter is: "; 
        Intent notificationIntent = new Intent(context, 
          Main.class); 
        PendingIntent contentIntent = PendingIntent 
          .getActivity(context, 0, notificationIntent, 0); 

        notification.setLatestEventInfo(context, contentTitle, 
          contentText, contentIntent); 

        mNotificationManager.notify(1, notification); 
        // Log.d("test", "Saving Data to File from Service."); 
+0

也不工作,謝謝你的幫助,但你確定這個代碼甚至可以用於服務? – 2012-07-22 10:49:25

+0

是的,這是有效的,因爲我從我的服務中複製它。讓我給你完整的代碼,你可以根據需要使用它。編輯我的答案 – Waqas 2012-07-22 11:00:39

+0

現在檢查它,我編輯了我的答案。 – Waqas 2012-07-22 11:40:46

3

下面一行:

PendingIntent activity = PendingIntent.getService(this, 0, intent, 0); 

應該這樣看:

PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0); 

,因爲你要開始一個Activity,而不是一個Service。希望這可以幫助。

+0

謝謝你的幫助,但它不工作,通知文本不顯示(在正常狀態下,當我點擊時,我有通知欄與我的通知,但在這裏的通知欄是空的) – 2012-07-22 10:40:32

+0

@Yasmine GreenApple,確保代碼確實被執行。順便說一下,您使用的Notification初始化模式已被棄用,請查看Notification.Builder類,因爲它是現在構建通知的首選方式。 – Egor 2012-07-22 11:42:17