在从FirebaseMessagingService扩展的类中找不到getApplicationContext()

问题描述 投票:0回答:1

我想通过Firebase发送和接收远程通知,但是我的自定义类找不到getApplicationContext()方法。

据我了解,FirebaseMessagingService扩展了Service, which extendsContextWrapper`,该服务扩展了Context。

所以我不知道getApplicationContext()不起作用。任何帮助将不胜感激!

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FirebaseMessageService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        if(remoteMessage.getNotification() != null){
            String title = remoteMessage.getNotification().getTitle();
            String text = remoteMessage.getNotification().getBody();

            NotificationHelper.displayNotification(getApplicationContext(), title, text);
        }
        super.onMessageReceived(remoteMessage);
    }
}

这是我的AndroidManifest.xml文件。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mealz">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <activity android:name=".Activities.UserActivity"></activity>
        <activity android:name=".Activities.LoginActivity" />
        <activity android:name=".Activities.SignupActivity" />
        <activity android:name=".Activities.SearchRecipeActivity" />
        <activity android:name=".Activities.RecipeDetailActivity" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
        </activity>

        <service android:name=".Notifications.FirebaseMessageService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
             </intent-filter>
        </service>
    </application>
</manifest>
android firebase firebase-cloud-messaging android-service
1个回答
1
投票

[您可以通过多种方式实现此目的,一种方法是保持上下文的弱引用,使应用程序类扩展android.app.application并在其上创建方法,并创建上下文的弱引用的变量,并将其分配给getApplicationContext()并且您可以在任意位置使用此上下文。

public class app extends android.app.Application{

        private static WeakReference<Context> referenceCntx;

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

            referenceCntx = new WeakReference<>(getApplicationContext());
        }

        public static Context getApplicationCntx(){
            return referenceCntx.get();
        }
    }

并且不要忘记在清单中添加此行

<application
        android:name=".app"
© www.soinside.com 2019 - 2024. All rights reserved.