当我尝试通知某些事件时发生空错误
嗨,大家好我是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)
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();
}
}
}
需要Context
从外面Activity
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
访问NotificationManager
,也是你的logcat中明确表示
java.lang.IllegalStateException:系统服务不可用于 onC之前的活动reate()
只能的Activity
它的工作原理,但是,当调试停止时,通知消失:0 – 2014-10-31 11:24:55
它工作正常,问题是我做了两个通知,所以...我怎么能做到这两个? @MD – 2014-10-31 11:32:53
@PierpaoloErcoli我没有得到它。你在说什么? – 2014-10-31 11:35:10
发布完整日志。 – 2014-10-31 11:13:56
好吧,一秒@kalyanpvs – 2014-10-31 11:14:26