2013-04-05 25 views
1

原諒我,但我無法通過NotificationBuilder的notify()方法調用。我有這樣的代碼:無法同步通知來通知()

timer.scheduleAtFixedRate(
       new TimerTask() { 
       @Override 
       public void run() { 
        synchronized (this) { 
      Builder notif = new NotificationCompat.Builder(c); 
     notif.setContentIntent(contIntent) 
       .setWhen(System.currentTimeMillis()) 
       .setTicker("Notification ticker") 
       .setSmallIcon(R.drawable.ic_launcher) 
       .setContentTitle("Vinceri") 
       .setContentText("Ha recibido una oferta de trabajo") 
       .setAutoCancel(true); 

     notif.notify(); 
     } 
} 
} 

而且無論身在何處,我把synchronized塊時,我得到相同的異常:

04-05 10:42:55.116: E/AndroidRuntime(18244): FATAL EXCEPTION: Timer-0 
04-05 10:42:55.116: E/AndroidRuntime(18244): java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll() 
04-05 10:42:55.116: E/AndroidRuntime(18244): at java.lang.Object.notifyAll(Native Method) 
04-05 10:42:55.116: E/AndroidRuntime(18244): at com.publidirecta.vinceriazafata.NotificationService$1.run(NotificationService.java:126) 
04-05 10:42:55.116: E/AndroidRuntime(18244): at java.util.Timer$TimerImpl.run(Timer.java:284) 

它也許noob問題,但...我必須做沒有收到該例外?謝謝。

+0

什麼是你想在這個代碼做... – 2013-04-05 08:47:50

+1

你需要鎖定'notif'對象。但是你在'this'上同步。 – 2013-04-05 08:49:23

+0

愚蠢的問題。謝謝!如果你把它放在一個答案中,我會upvote你。 – Fustigador 2013-04-05 08:51:39

回答

3

假設你正在嘗試添加通知到Android通知抽屜..你需要做以下幾點:?

Builder notif = new NotificationCompat.Builder(c); 
     notif.setContentIntent(contIntent) 
       .setWhen(System.currentTimeMillis()) 
       .setTicker("Notification ticker") 
       .setSmallIcon(R.drawable.ic_launcher) 
       .setContentTitle("Vinceri") 
       .setContentText("Ha recibido una oferta de trabajo") 
       .setAutoCancel(true); 
     //create notification from builder 
     Notification notification = notif.build(); 
     //get instance of NotificationManager 
     NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     //call notify method of NotificationManager to add this notification to android notification drawer.. 
     notificationmanager.notify(0, notification); 
+0

這比我問的還要多。非常感謝你Praful。 – Fustigador 2013-04-05 08:57:57