首页 > 解决方案 > 设置任务描述时android应用程序崩溃

问题描述

我正在尝试使用以下代码设置任务描述

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        String title = "F App";
        int icon = R.drawable.circle;
        int color = R.color.red;

        ActivityManager.TaskDescription description = new ActivityManager.TaskDescription(title, icon, color);
        this.setTaskDescription(description);

    }

这是错误日志

java.lang.NoSuchMethodError: No direct method <init>(Ljava/lang/String;II)V in class Landroid/app/ActivityManager$TaskDescription; or its super classes (declaration of 'android.app.ActivityManager$TaskDescription' appears in /system/framework/framework.jar)
        at com.myapp.app.main.home.galaxy.FAppActivity.onViewsInitialised(FAppActivity.java:36)
        at com.myapp.app.common.BaseActivity.onCreate(BaseActivity.java:47)
        at android.app.Activity.performCreate(Activity.java:7030)
        at android.app.Activity.performCreate(Activity.java:7021)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2773)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2898)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1624)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6549)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)

我搜索了一些线程[不是伴随错误,但有些相似],发现某些依赖项可能正在使用旧版本的支持库并且可能没有该方法。不知道有没有影响!

在我的 app.gradle 中使用androidx.appcompat:appcompat:1.1.0和编译 sdk 版本28和 sdk 工具版本28.0.3

如果您对此类问题有所了解,请提供帮助

标签: androidandroid-studio

解决方案


您正在使用仅在 API.28 (Android P) 上可用的三参数构造函数

如果要使用 API 21,则必须使用单参数构造函数或已弃用的使用 a而不是图标 int 资源的3 参数构造函数。Bitmap

所以要让你的代码工作

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {

    String title = "F App";
    int icon = R.drawable.circle;
    int color = R.color.red;

    ActivityManager.TaskDescription description = new ActivityManager.TaskDescription(title, icon, color);
    this.setTaskDescription(description);

} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

    String title = "F App";
    Bitmap icon = .....
    int color = R.color.red;

    ActivityManager.TaskDescription description = new ActivityManager.TaskDescription(title, icon, color);
    this.setTaskDescription(description);

}

推荐阅读