我正在努力使Firbase Push通知起作用:
我的Android清单文件中有以下服务:
<service android:name=".notifications.MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name=".notifications.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 = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(Constants.FIREBASE_TOKEN, refreshedToken).apply();
}
}
我的StartActivity由以下内容组成
public class StartActivity extends AppCompatActivity {
public static boolean isAppRunning;
private SharedPreferences mSharedPreferences;
private final String TAG="token";
private String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
startService(new Intent(this,MyFirebaseInstanceIDService.class));
mSharedPreferences = getSharedPreferences(Constants.FIREBASE_TOKEN, MODE_PRIVATE);
token=mSharedPreferences.getString(Constants.FIREBASE_TOKEN,"");
Log.d(TAG, "token:" + token);
}
}
您会看到我手动启动了服务(不确定是否必须这样做),但是问题是令牌始终为空。