Firebasemessage服务未初始化时未收到Firebase通知

时间:2018-08-03 10:34:35

标签: android firebase

实际上,我要启动Firebase消息服务取决于应用程序要求。以编程方式启动Firebase消息服务之前,我正在发送一条未收到的通知,但是以编程方式启动Firebase消息服务并发送通知之后,此通知也未收到。我不明白为什么会这样。

 Logging event (FE): notification_receive(_nr), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=2530909691907984364}]
   Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=2530909691907984364}]

I am stopping service like this

     ComponentName componentName3 = new ComponentName(context, FirebasefcmService.class);
                context.getPackageManager().setComponentEnabledSetting(componentName3,
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);

1 个答案:

答案 0 :(得分:0)

用于Oreo设备上的Firebase推送通知

1。将此元数据写入清单文件中

<service android:name=".CustomFirebaseMessagingService">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
    <action android:name=".SplashActivity" />
  </intent-filter>
</service>
<service android:name=".CustomFirebaseInstanceIDService">
   <intent-filter>
     <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
   </intent-filter>
</service>
<service
    android:name=".RegistrationIntentService"
    android:exported="false" />
    
<meta-data       
android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id"/>

2。用于注册设备以推送通知

public class RegistrationIntentService extends IntentService {
    // abbreviated tag name
    private static final String TAG = RegistrationIntentService.class.getSimpleName();
    private String android_id;
    public RegistrationIntentService() {
        super(TAG);
    }
    String token;
    @Override
    protected void onHandleIntent(Intent intent) {

        // Make a call to Instance API

        FirebaseInstanceId instanceID = FirebaseInstanceId.getInstance();

        
        //String senderId = getResources().getString(R.string.gcm_defaultSenderId);

        // request token that will be used by the server to send push notifications
        token = instanceID.getToken();
        Log.d(TAG, "FCM Registration Token: " + token);
    }
}

3。刷新设备令牌服务类以将新令牌注册到Firebase

public class CustomFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = CustomFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}

4。用于在前台接收推送通知

public class CustomFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = CustomFirebaseMessagingService.class.getSimpleName();
    private NotificationManager mNotificationManager;
    private int notificationID = 100;
    private int numMessages = 0;
    String title, message, image;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            title = remoteMessage.getData().get("title");
            message = remoteMessage.getData().get("body");
            image = remoteMessage.getData().get("icon");
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            title = remoteMessage.getNotification().getTitle();
            message = remoteMessage.getNotification().getBody();
            image = remoteMessage.getData().get("image");
        }

        displayNotification(getApplicationContext(),title,message,image);

    }

    protected void displayNotification(Context context, String PUSH_TITLE, String PUSH_MSG, String PUSH_IMAGE) {
        Log.i("Start", "notification");

        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

	      /* Invoking the default notification service */
        NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
        mBuilder.setContentTitle(PUSH_TITLE);
        mBuilder.setContentText(PUSH_MSG);
        mBuilder.setTicker("Message from "+getResources().getString(R.string.app_name));
        mBuilder.setSmallIcon(R.drawable.notification_icon);
        mBuilder.setLargeIcon(icon);
	      	/* Increase notification number every time a new notification arrives */
        mBuilder.setNumber(++numMessages);
        System.out.println("Push image:"+PUSH_IMAGE);
        NotificationCompat.BigTextStyle notiStyle = new
                NotificationCompat.BigTextStyle();
        notiStyle.setBigContentTitle(PUSH_TITLE);
        notiStyle.bigText(PUSH_MSG);
        mBuilder.setStyle(notiStyle);
	      	/* Creates an explicit intent for an Activity in your app */
        Intent resultIntent = new Intent(context, SplashActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(SplashActivity.class);

	      	/* Adds the Intent that starts the Activity to the top of the stack */
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.setAutoCancel(true);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Sets an ID for the notification, so it can be updated.
            String CHANNEL_ID = getResources().getString(R.string.default_notification_channel_id);// The id of the channel.
            CharSequence name = getString(R.string.app_name);// The user-visible name of the channel.
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            mChannel.setSound(null, null);
            mNotificationManager.createNotificationChannel(mChannel);
            mBuilder.setChannelId(CHANNEL_ID);
        }
	      /* notificationID allows you to update the notification later on. */
        mNotificationManager.notify(notificationID, mBuilder.build());
    }
}