2013-04-05 27 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