如何为自定义应用程序投射上下文 class

how to cast context for custom Application class

我正在开发逻辑来检查我的应用程序是否在前台使用自定义应用程序 class。当我尝试在 MyFirebaseMessagingService.java 中转换 class 时,出现错误。代码如下所示。

boolean isForeground = ((MyAppStatus)getApplication()).isForeground();

此外,我尝试使用如下代码。

boolean isForeground = MyAppStatus.get(getApplicationContext).isForeground();

boolean isForeground = MyAppStatus.get(getApplication).isForeground();

但是,我遇到了同样的转换错误。

自定义应用class的代码如下所示。

public class MyAppStatus extends Application {
    private AppStatus mAppStatus = AppStatus.FOREGROUND;

    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
    }

    public static MyAppStatus get(Context context) {
        return (MyAppStatus)context.getApplicationContext();
    }

    public AppStatus getAppStatus() {
        return mAppStatus;
    }

    // check if app is foreground
    public boolean isForeground() {
        return mAppStatus.ordinal() > AppStatus.BACKGROUND.ordinal();
    }

    public enum AppStatus {
        BACKGROUND,                // app is background
        RETURNED_TO_FOREGROUND,    // app returned to foreground(or first launch)
        FOREGROUND;                // app is foreground
    }

错误如下。

12-10 22:26:59.256 32544-32633/com.forwards.android.goodhus E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1
                                                                          Process: com.XXXXXX.android.XXXXXX, PID: 32544
                                                                          java.lang.ClassCastException: android.app.Application cannot be cast to com.XXXXXX.android.XXXXXX.common.utils.MyAppStatus
                                                                              at com.XXXXXX.android.XXXXXX.common.fcm.MyFirebaseMessagingService.sendToNotificationCenter(MyFirebaseMessagingService.java:187)

一些经验丰富的人会很有帮助。 提前致谢。

您需要在清单 application 标签中注册您的 MyAppStatus class,例如

 <application
        android:name=".MyAppStatus"

尝试使用 getApplicationContext() 代替:

boolean isForeground = ((MyAppStatus)getApplicationContext()).isForeground();

并确保在清单中的应用程序标记中使用 android:name=".MyAppStatus" 设置应用程序。否则你会得到错误的对象