19

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"

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Android teem
  • 780
  • 2
  • 13
  • 36
  • What specific error are you getting? Post the log. – Jay Oct 10 '18 at 09:46
  • FirebaseMessagingService extends EnhancedIntentService which then extends Service. Using `this` should work. If that doesn't, type `context` and check your auto complete – Zun Oct 10 '18 at 09:48
  • Post snippet of `CustomSharedPreferences`. – Jay Oct 10 '18 at 09:48
  • @Jay posted....... – Android teem Oct 10 '18 at 09:59
  • Your code compiles fine for me. Check your imports, is it `import android.content.Context;` in `CustomSharedPreferences.java`? Where exactly is that error shown? Have you tried to use `Build>Clean Project`? Is your gradle in sync? What version of `com.google.firebase:firebase-messaging:??` are you using? – zapl Oct 10 '18 at 10:03
  • @zapl to me the error is fine and my apps run fine, but it showing error in editor – Android teem Oct 10 '18 at 10:31
  • Maybe if you restart Android studio. There should be no error if everything is correct with your code, especially if it compiles and runs fine – zapl Oct 10 '18 at 11:41
  • Not understanding the downvoting on his question. I have a similar issue when my app is in the background or closed. We want to show notifications but drawables and such are not available as there is not really a context – Verthosa Feb 14 '19 at 09:18

5 Answers5

19

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

Harish Kamboj
  • 887
  • 12
  • 32
3

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.

Fadils
  • 1,508
  • 16
  • 21
2
FirebaseMessagingService extends Service 

and

Service extends ContextWrapper

and

ContextWrapper extends Context

so it is a Context as well, so use MyFirebaseMessagingService.this or simply this.

deHaar
  • 17,687
  • 10
  • 38
  • 51
1

If someone is still struggling with this problem, here is the solution:

To be able to get the context inside any Service you should do that in onCreate method, otherwise you'll face the NullPointerException

@Override
public void onCreate() {
    super.onCreate();
    context = this;
}
Ion
  • 81
  • 1
  • 9
0

Add the following code, here is your CustomSharedPreferences class.

public class SharedHelper
 {
    public static SharedPreferences sharedPreferences;
    public static SharedPreferences.Editor editor;
    public static void putKey(Context context, String Key, String Value) {
        sharedPreferences = context.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.putString(Key, Value);
        editor.apply();

    }

    public static String getKey(Context context, String Key) {
        sharedPreferences = context.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);
        return sharedPreferences.getString(Key, "");
    }
}

after that add following code add in FirebaseMessagingService.class

    @Override
public void onNewToken(String s) {
    super.onNewToken(s);

    @SuppressLint("HardwareIds")
    String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

    Log.d("DEVICE_ID: " , deviceId);
    Log.d("FCM_TOKEN",s);

    SharedHelper.putKey(this, "device_token", s);
    SharedHelper.putKey(this, "device_id", deviceId);
}

don't initialize your CustomSharedPreferences inside FirebaseMessagingService class it may help you.

Ram Suthakar
  • 275
  • 2
  • 15