NotificationUtils.java
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
}
}