2014-10-31 75 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