如何为自定义Application类转换上下文

时间:2017-12-10 13:50:22

标签: java android android-lifecycle

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

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

另外,我尝试使用下面的代码。

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

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

但是,我遇到了同样的施法错误。

自定义Application类的代码如下所示。

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)

一些有丰富经验的人会有很大的帮助。 非常感谢。

2 个答案:

答案 0 :(得分:2)

您需要在清单MyAppStatus标记中注册application课程,例如

 <application
        android:name=".MyAppStatus"

答案 1 :(得分:0)

请尝试使用getApplicationContext()

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

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