我在onTokenRefresh
方法
以下是我的清单文件
<uses-permission android:name="android.permission.INTERNET" />
<service
android:name=".fcmService.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".fcmService.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
以下是我的MyFirebaseInstanceIDService
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "@@ onTokenRefresh: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
// Saving reg id to shared preferences
storeRegIdInPref(refreshedToken);
}
}
我在Splash屏幕中调用MyFirebaseInstanceIDService
就像这样..
MyFirebaseInstanceIDService myFirebaseInstanceIdService = new MyFirebaseInstanceIDService();
myFirebaseInstanceIdService.onTokenRefresh();
提前感谢您的帮助。
答案 0 :(得分:1)
你不能使用它的实例来调用服务方法,因为它需要在工作线程上运行,
您必须启动该服务并使用其他服务获取令牌。
只要当前令牌无效,FCM就会调用令牌刷新
通过扩展IntentService类
来创建另一个服务@Override
protected void onHandleIntent(Intent intent) {
try {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + token);
// [END get_token]
sendRegistrationToServer(token);
// Subscribe to topic channels
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
// [END register_for_gcm]
} catch (Exception e) {
Log.e(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
}
}
您还可以从onTokenRefresh()方法启动上述服务,以避免代码复制。
答案 1 :(得分:0)
onTokenRefresh 。如果您的应用先前已安装并生成了令牌,则不会调用onTokenRefresh
。尝试卸载并重新安装应用程序以强制生成新令牌,这将导致调用onTokenRefresh。
试试这个,你忘记在super.onTokenRefresh();
onTokenRefresh
() method
public class FirebaseServiceId extends FirebaseInstanceIdService {
public static final String TAG = "FirebaseId";
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.e(TAG, "Refresh token is: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
Log.e(TAG, "Token2:" + token);
}
}
试试这个你可以像这样生成你的标记
String tonk = FirebaseInstanceId.getInstance().getToken();
Log.e("Tok: ", tonk + "");
答案 2 :(得分:0)
使用以下代码获取令牌。 所以问题来自于你不能在你的AndroidManifest.xml(内部标签)中使用这一行:
tools:node="merge"
Firebase无法在您的应用中使用。至少,这是我修复我的应用程序以最终获得有效令牌的方式!