我应如何为现有的Firebase通知类分配通知渠道?

时间:2018-08-19 16:54:19

标签: android firebase notifications firebase-cloud-messaging

我使用Firebase将通知发送到我的应用,并通过通知数据的点击操作打开某些活动。问题是,在API级别<26的情况下,它可以正常工作。但是对于新版本,所有通知都必须分配给一个频道。但是我不确定如何为现有系统分配一个可以在API级别26或更高级别上运行的通道?

这是我的FirebaseMessagingService Java类:

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
    private static final String TAG = "FirebaseMessagingServic";

    public FirebaseMessagingService() {}

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            try {
                JSONObject data = new JSONObject(remoteMessage.getData());
                String jsonMessage = data.getString("extra_information");
                Log.d(TAG, "onMessageReceived: \n" +
                    "Extra Information: " + jsonMessage);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle(); //get title
            String message = remoteMessage.getNotification().getBody(); //get message
            String click_action = remoteMessage.getNotification().getClickAction(); //get click_action

            Log.d(TAG, "Message Notification Title: " + title);
            Log.d(TAG, "Message Notification Body: " + message);
            Log.d(TAG, "Message Notification click_action: " + click_action);

            sendNotification(title, message, click_action);
        }
    }

    @Override
    public void onDeletedMessages() {

    }

    private void sendNotification(String title, String messageBody, String click_action) {
        Intent intent;
        if (click_action.equals("SOMEACTIVITY")) {
            intent = new Intent(this, SomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else {
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */ , intent,
            PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */ , notificationBuilder.build());
    }
}

我很好奇我应该在此处更改将其分配给频道吗?

我还在下面分享我的ActivityMain活动和清单XML:

public class MainActivity {

    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();
        FirebaseMessaging.getInstance().subscribeToTopic("DAILYDOSE");
    }

}

清单:

<application
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:roundIcon="@mipmap/ic_launcher_round"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">
   <activity android:name=".MainActivity">
      <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
   </activity>
   <activity android:name=".SomeActivity">
      <intent-filter>
         <action android:name="SOMEACTIVITY" />
         <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
   </activity>
   <service android:name=".FirebaseMessagingService">
      <intent-filter>
         <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
   </service>
   <meta-data
      android:name="com.google.firebase.messaging.default_notification_color"
      android:resource="@color/colorAccent" />
</application>

2 个答案:

答案 0 :(得分:2)

要使用频道,您需要在创建通知之前创建一个channelId。您可以在创建服务时创建频道ID,例如

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    private static final String CHANNEL_ID = "default";
    private static final String CHANNEL_DESCRIPTION = "Your description...";

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_DESCRIPTION, NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }
}

这将允许您在创建通知时使用频道ID,即

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)

答案 1 :(得分:0)

使用其原始值创建现有的通知渠道不会执行任何操作,因此在启动应用程序时可以安全地调用此代码。 https://developer.android.com/training/notify-user/channels#CreateChannel就是在这里解释的。

重要的是channelId,在所有调用中都必须保持一致:在创建频道时,并作为NotificationCompat.Builder()的参数。