NotificationManager getSystemService()调用报错,请求解决方法
解决
getSystemService(NotificationManager.class)报错问题 这个报错是因为你调用的getSystemService方法参数不匹配——要么是在非Context类中错误调用了其他重载方法,要么是没有适配API版本要求。
两种解决方式:
兼容所有Android版本:
使用字符串常量Context.NOTIFICATION_SERVICE作为参数,再强制转换类型:import android.content.Context; import android.app.NotificationManager; // ... NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);仅适配API 23及以上版本:
确保你在Context子类(比如Activity、Service)中调用,或者持有有效的Context实例:// 在Activity/Service内部直接调用 NotificationManager notificationManager = getSystemService(NotificationManager.class); // 在非Context类中,传入Context对象调用 NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
额外注意:
如果你的代码不在Context子类里,直接写getSystemService可能会调用到其他类的同名方法,导致参数类型不匹配,这时候一定要通过Context实例来调用该方法。
内容的提问来源于stack exchange,提问作者k1r4n
相关产品推荐
相关产品推荐

