Android - setStatusBarColor() NoSuchMethodError 异常

Android - setStatusBarColor() NoSuchMethodError exception

我在 Google Play 上发布了我的 Android 应用程序,我收到许多关于某些设备崩溃的报告。一开始以为是SDK版本的问题,更新后还是这样。这是我得到的报告日志:

java.lang.NoSuchMethodError: android.view.Window.setStatusBarColor
at stefanmaimon.milab.blenders.MainActivity.onCreate(MainActivity.java:81)
at android.app.Activity.performCreate(Activity.java:5451)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.access0(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)

这是 MainActivity class 处的第 81 行:

if (android.os.Build.VERSION.SDK_INT >= 19) {
    Window statusBar = getWindow();
    statusBar.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    statusBar.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    statusBar.setStatusBarColor(Color.parseColor("#111111")); <--- LINE 81
}

它通常在以下设备中崩溃:Galaxy S5 (kltecan)、Galaxy S2 Plus (s2vep)、alps..

需要

if (android.os.Build.VERSION.SDK_INT >= 21)

而不是

if (android.os.Build.VERSION.SDK_INT >= 19)

因为 setStatusBarColor() 已添加到 API 级别 21。

编辑:你可以像这样使用:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          //your code
        }

使用这个:

if (android.os.Build.VERSION.SDK_INT >= 21) {
    Window statusBar = getWindow();
    statusBar.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    statusBar.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    statusBar.setStatusBarColor(Color.parseColor("#111111"));  }