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



我想通过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.app.application及其create方法的应用程序类,并创建一个上下文弱引用的变量,并将其分配给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"

最新更新