通过context.getSystemService()方法获取***Manager实例的类,反射获取其public方法,比如反射调用NotificationManager的createNotificationChannel方法:
android O的通知新特性,要求发送通知前设置channel,为兼容低版本,可以添加sdk判断来选择实例化NotificationManager的方法:
public static NotificationManager getNotificationManager(Context context) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= ToucConstants.VERSION_CODES_O) { NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_MIN); try { final Method setSystemControlCenterEnable = Class.forName("android.app.NotificationManager").getMethod("createNotificationChannel", new Class[]{NotificationChannel.class}); setSystemControlCenterEnable.invoke(notificationManager, channel); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return notificationManager; }