NotificationUtils.java 1.73 KB
package com.wd.common.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class NotificationUtils {
    private static final String ACTION_NOTIFICATION = "com.example.app.ACTION_NOTIFICATION";
    private static final String EXTRA_MESSAGE = "message";
    private Context context;
    private NotificationListener notificationListener;
    private BroadcastReceiver notificationReceiver;
    public NotificationUtils(Context context, NotificationListener notificationListener) {
        this.context = context;
        this.notificationListener = notificationListener;
        setupBroadcastReceiver();
    }
    public void sendNotification(String message) {
        Intent intent = new Intent(ACTION_NOTIFICATION);
        intent.putExtra(EXTRA_MESSAGE, message);
        context.sendBroadcast(intent);
    }
    private void setupBroadcastReceiver() {
        notificationReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (notificationListener != null) {
                    String message = intent.getStringExtra(EXTRA_MESSAGE);
                    notificationListener.onNotificationReceived(message);
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter(ACTION_NOTIFICATION);
        context.registerReceiver(notificationReceiver, intentFilter);
    }
    public void unregisterReceiver() {
        if (notificationReceiver != null) {
            context.unregisterReceiver(notificationReceiver);
        }
    }
    public interface NotificationListener {
        void onNotificationReceived(String message);
    }
}