如何在FirebaseMessagingService中获取上下文? [英] how to get the Context Inside the FirebaseMessagingService?
问题描述
我有一个应用程序,它使用FCM发送和接收消息.我已经按照文档中的建议实施了所有操作.
I have an app and It Uses FCM for sending and receiving messages. I have implemented every thing as suggested in docs.
现在在生成令牌时,我想将其保存到共享首选项中.但这给了错误.
Now on generation of token I want to save that into the Shared Preferrences. but it is giving error on that .
考虑类的名称就像
public class MyFirebaseMsgAndTokenService extends FirebaseMessagingService {
private static final String TAG = "C_MyFirebaseIIDService";
@Override
public void onNewToken(String newToken) {
super.onNewToken(newToken);
Log.d(TAG, "Refreshed token: " + newToken);
CustomSharedPreferences customSharedPreferences = new CustomSharedPreferences(this); // giving error on this
String oldToken = customSharedPreferences.getStringData(FCM_GENERATED_TOKEN);
sendRegistrationToServer(newToken,oldToken);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
try {
} catch (Exception e) {
}
}}
我真的很想在此服务中将令牌保存到我的应用程序中.请告诉我为什么我无法获得参考/上下文?
I really want to save the token into my app here in this service. Please tell me why I am not able to get the reference/Context ?
更新:我的CustomSharedPrefernces是一个将数据保存到sharedPrefernces中的类
public class CustomSharedPreferences {
public static final String FCM_GENERATED_TOKEN = "FCM_GENERATED_TOKEN";
private static CustomSharedPreferences mCustomSharedPreferences;
private final SharedPreferences sharedPreferences;
public static CustomSharedPreferences getInstance(Context context) {
if (mCustomSharedPreferences == null) {
mCustomSharedPreferences = new CustomSharedPreferences(context);
}
return mCustomSharedPreferences;
}
public CustomSharedPreferences(Context context) {
sharedPreferences = context.getSharedPreferences("myApp", Context.MODE_PRIVATE);
}}
更新:
错误:"CustomSharedPreferences中的android.content.context无法应用于com.myprojectname.MyFireBaseMsgAndTokenService"
error: "android.content.context in CustomSharedPreferences can not be applied to com.myprojectname.MyFireBaseMsgAndTokenService"
推荐答案
您可以在此处查看我的firebase通知处理:
You can see my firebase notification handling here:
public UserPreferences(Context context) {
this.context = context;
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
您可以简单地使用this
或getApplicationContext()
来获取上下文
You can use simply use this
orgetApplicationContext()
to get the context
这篇关于如何在FirebaseMessagingService中获取上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!