当我尝试通知某些内容时出现空错误

时间:2014-10-31 11:11:51

标签: android notifications

嗨,伙计们,我刚开始使用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(由于三星股票ROM导致Pause GC错误错误)

2 个答案:

答案 0 :(得分:3)

您需要Context才能从外部NotificationManager

访问Activity
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

并且你的logcat也清楚地说了

  

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

您只能在NotificationManager onCreate()

之后访问Activity

答案 1 :(得分:2)

是因为它没有在你的班级中找到上下文:

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();
    }
}
}