Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the Context Inside the FirebaseMessagingService?

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 .

Consider the name of class is like

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 ?

update: My CustomSharedPrefernces is a class which is saving data in to 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);
}}

Update:

error: "android.content.context in CustomSharedPreferences can not be applied to com.myprojectname.MyFireBaseMsgAndTokenService"

like image 639
Android teem Avatar asked Oct 10 '18 09:10

Android teem


2 Answers

You can see my firebase notification handling here:

enter image description here

public UserPreferences(Context context) {
        this.context = context;
        preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

You can use simply use this orgetApplicationContext() to get the context

like image 151
Harish Kamboj Avatar answered Oct 10 '22 06:10

Harish Kamboj


For me, I just upgraded my Firebase Messaging to the latest (which during this time of writing 20.2.0).

implementation 'com.google.firebase:firebase-messaging:20.2.0'

Then somehow suddenly I can pass this again.

like image 42
Fadils Avatar answered Oct 10 '22 06:10

Fadils