2014-10-31 70 views
0

嗨,大家好我是Android的开始,我试图从与我的主要活动不同的类发出通知。但e.printStackTrace()声明为“null”,并停在行:“NotificationManager notificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);”如果我从mainActivity发出同样的通知一切顺利。你能帮我吗?当我尝试通知某些事件时发生空错误

if(giorni_di_differenza <= 15) 
{ 

    try{ 
     PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); 
     NotificationCompat.Builder n = new NotificationCompat.Builder(context) 
      .setContentTitle(nome_evento) 
      .setContentText(descrizione_evento) 
      .setContentIntent(pi) 
      .setAutoCancel(true) 
      .setLights(Color.GREEN, 1000, 1000) 
      .setSmallIcon(R.drawable.ic_launcher); 

     NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

     notificationManager.notify(0, n.build()); 

    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 

如果您需要更多代码,我可以寄给您。

的logcat:http://pastebin.com/W4hKbf6W(暂停GC错误是错误的,由于三星股票ROM)

+0

发布完整日志。 – 2014-10-31 11:13:56

+0

好吧,一秒@kalyanpvs – 2014-10-31 11:14:26

回答

2

onCreate()后访问NotificationManager雅,因为它没有找到在类方面:

NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

做这样的:

//pass different id for different notifications 
private void showNotification(Context con, int notificationID) { 
    if(giorni_di_differenza <= 15) 
    { 

     try{ 
      PendingIntent pi = PendingIntent.getActivity(con, 0, new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); 
      NotificationCompat.Builder n = new NotificationCompat.Builder(con) 
       .setContentTitle(nome_evento) 
       .setContentText(descrizione_evento) 
       .setContentIntent(pi) 
       .setAutoCancel(true) 
       .setLights(Color.GREEN, 1000, 1000) 
       .setSmallIcon(R.drawable.ic_launcher); 
     NotificationManager notificationManager = (NotificationManager) con.getSystemService(NOTIFICATION_SERVICE); 

     notificationManager.notify(notificationID, n.build()); 

    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 
} 
+0

''NotificationID'它工作正常,问题是我做了两个通知等......我怎么能做到这两件事? @Hamad – 2014-10-31 11:33:11

+1

改变这个:notificationManager.notify(0,n.build()); to this notificationManager.notify(1,n.build()); – Hamad 2014-10-31 11:39:58

+0

查看已更新的答案 – Hamad 2014-10-31 11:40:53

3

需要Context从外面Activity

NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); 

访问NotificationManager,也是你的logcat中明确表示

java.lang.IllegalStateException:系统服务不可用于 onC之前的活动reate()

只能的Activity

+0

它的工作原理,但是,当调试停止时,通知消失:0 – 2014-10-31 11:24:55

+0

它工作正常,问题是我做了两个通知,所以...我怎么能做到这两个? @MD – 2014-10-31 11:32:53

+0

@PierpaoloErcoli我没有得到它。你在说什么? – 2014-10-31 11:35:10

相关问题