我似乎無法接收FCM推送通知,這是我在Android上終止應用程序後從FCM控制檯發送的,因爲在長按「概覽」按鈕並輕掃應用程序以終止。當應用程序在前臺或後臺運行時,它工作得很好。這可能看起來像一個重複的問題,但我嘗試了其他方法,但我仍然無法得到它。應用程序死亡後的推送通知
NotificationService.java
public class NotificationService extends FirebaseMessagingService
{
private static final String TAG = "FCM Service";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
TokenRefresh.java
public class TokenRefresh extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("global");
String token = ("fcm"+ FirebaseInstanceId.getInstance().getToken());
}
}
查看下面鏈接中的第一個答案;-) http://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase玩得開心 –
@ AL。我嘗試從POST發送數據消息,但是當我將它發送到我的應用程序時,應用程序崩潰。我可以通過POST正常接收通知,而不是通過POST發送數據消息,但是沒有數據消息,我的代碼是否有問題或者清單中接收數據消息需要額外的東西? – Tyson
你可以發佈堆棧跟蹤嗎? –