This response does not destroy the instance id; instead, it can get the current one. It also keeps updated in general preferences.
strings.xml
<string name="pref_firebase_instance_id_key">pref_firebase_instance_id</string> <string name="pref_firebase_instance_id_default_key">default</string>
Utility.java (any class where you want to set / get settings)
public static void setFirebaseInstanceId(Context context, String InstanceId) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor; editor = sharedPreferences.edit(); editor.putString(context.getString(R.string.pref_firebase_instance_id_key),InstanceId); editor.apply(); } public static String getFirebaseInstanceId(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String key = context.getString(R.string.pref_firebase_instance_id_key); String default_value = context.getString(R.string.pref_firebase_instance_id_default_key); return sharedPreferences.getString(key, default_value); }
MyFirebaseInstanceIdService.java (extends FirebaseInstanceIdService)
@Override public void onCreate() { String CurrentToken = FirebaseInstanceId.getInstance().getToken(); //Log.d(this.getClass().getSimpleName(),"Inside Instance on onCreate"); String savedToken = Utility.getFirebaseInstanceId(getApplicationContext()); String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key); if(CurrentToken != null && !savedToken.equalsIgnoreCase(defaultToken)) //currentToken is null when app is first installed and token is not available //also skip if token is already saved in preferences... { Utility.setFirebaseInstanceId(getApplicationContext(),CurrentToken); } super.onCreate(); } @Override public void onTokenRefresh() { .... prev code Utility.setFirebaseInstanceId(getApplicationContext(),refreshedToken); ....
}
Android 2.0 and above onCreate service is not called when it starts automatically ( source ). Instead, onStartCommand overridden and used. But in the real FirebaseInstanceIdService, it is declared as final and cannot be overridden. However, when we start the service using startService (), if the service is already running, the original instance is used (which is good). Our onCreate () (defined above) is also called !.
Use this at the beginning of MainActivity or whichever you think you need an instance id for.
MyFirebaseInstanceIdService myFirebaseInstanceIdService = new MyFirebaseInstanceIdService(); Intent intent= new Intent(getApplicationContext(),myFirebaseInstanceIdService.getClass()); //Log.d(this.getClass().getSimpleName(),"Starting MyFirebaseInstanceIdService"); startService(intent); //invoke onCreate
And finally
Utility.getFirebaseInstanceId(getApplicationContext())
Note that you can improve this by trying to move the startervice () code into the getFirebaseInstanceId method.
Varun Garg Aug 23 '16 at 19:45 2016-08-23 19:45
source share