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

时间:2019-11-15 15:36:17

标签: android firebase firebase-cloud-messaging android-service

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

据我了解,FirebaseMessagingService扩展了服务, which extends ContextWrapper,后者扩展了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>

1 个答案:

答案 0 :(得分: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"