File: NotifyByAndroid.java

package info (click to toggle)
kf6-knotifications 6.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 22,072 kB
  • sloc: cpp: 3,183; java: 304; xml: 122; python: 24; sh: 14; makefile: 7; ansic: 4
file content (343 lines) | stat: -rw-r--r-- 15,711 bytes parent folder | download
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
    SPDX-FileCopyrightText: 2018 Volker Krause <vkrause@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

package org.kde.knotifications;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.RemoteInput;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import java.util.HashMap;
import java.util.HashSet;

/** Java side of the Android notification backend. */
public class NotifyByAndroid extends BroadcastReceiver
{
    private static final String TAG = "org.kde.knotifications";

    private static final String NOTIFICATION_ACTION = ".org.kde.knotifications.NOTIFICATION_ACTION";
    private static final String NOTIFICATION_DELETED = ".org.kde.knotifications.NOTIFICATION_DELETED";
    private static final String NOTIFICATION_OPENED = ".org.kde.knotifications.NOTIFICATION_OPENED";
    private static final String NOTIFICATION_REPLIED = ".org.kde.knotifications.NOTIFICATION_REPLIED";
    // the id of the notification triggering an intent
    private static final String NOTIFICATION_ID_EXTRA = "org.kde.knotifications.NOTIFICATION_ID";
    // the id of the action that was triggered for a notification
    private static final String NOTIFICATION_ACTION_ID_EXTRA = "org.kde.knotifications.NOTIFICATION_ACTION_ID";
    // the group a notification belongs too
    private static final String NOTIFICATION_GROUP_EXTRA = "org.kde.knotifications.NOTIFICATION_GROUP";
    // RemoteInput value key
    private static final String REMOTE_INPUT_KEY = "REPLY";

    // notification id offset for group summary notifications
    // we need this to stay out of the regular notification's id space (which comes from the C++ side)
    // and so we can distinguish if we received actions on regular notifications or group summaries
    private static final int NOTIFICATION_GROUP_ID_FLAG = (1 << 24);

    private android.content.Context m_ctx;
    private NotificationManager m_notificationManager;
    private int m_uniquePendingIntentId = 0;
    private HashSet<String> m_channels = new HashSet();

    private class GroupData {
        public HashSet<Integer> childIds = new HashSet();
        public int groupId;
    };
    private HashMap<String, GroupData> m_groupSummaries = new HashMap();

    public NotifyByAndroid(android.content.Context context)
    {
        Log.i(TAG, context.getPackageName());
        m_ctx = context;
        m_notificationManager = (NotificationManager)m_ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        IntentFilter filter = new IntentFilter();
        filter.addAction(m_ctx.getPackageName() + NOTIFICATION_ACTION);
        filter.addAction(m_ctx.getPackageName() + NOTIFICATION_DELETED);
        filter.addAction(m_ctx.getPackageName() + NOTIFICATION_OPENED);
        filter.addAction(m_ctx.getPackageName() + NOTIFICATION_REPLIED);

        if (Build.VERSION.SDK_INT >= 33) {
            m_ctx.registerReceiver(this, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            m_ctx.registerReceiver(this, filter);
        }
    }

    public void notify(KNotification notification)
    {
        Log.i(TAG, notification.text);

        // notification channel
        if (!m_channels.contains(notification.channelId)) {
            m_channels.add(notification.channelId);

            if (Build.VERSION.SDK_INT >= 26) {
                NotificationChannel channel = new NotificationChannel(notification.channelId, notification.channelName, NotificationManager.IMPORTANCE_DEFAULT);
                channel.setDescription(notification.channelDescription);

                switch (notification.urgency) {
                    case KNotification.CriticalUrgency:
                        channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
                        break;
                    case KNotification.NormalUrgency:
                        channel.setImportance(NotificationManager.IMPORTANCE_LOW);
                        break;
                    case KNotification.LowUrgency:
                        channel.setImportance(NotificationManager.IMPORTANCE_MIN);
                        break;
                    case KNotification.HighUrgency:
                    default:
                        channel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
                        break;
                }

                m_notificationManager.createNotificationChannel(channel);
            }
        }

        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= 26) {
            builder = new Notification.Builder(m_ctx, notification.channelId);
        } else {
            builder = new Notification.Builder(m_ctx);
        }

        if (Build.VERSION.SDK_INT >= 23) {
            builder.setSmallIcon((Icon)notification.icon);
        } else {
            builder.setSmallIcon(m_ctx.getApplicationInfo().icon);
        }
        builder.setContentTitle(notification.title);
        builder.setContentText(notification.text);
        // regular notifications show only a single line of content, if we have more
        // we need the "BigTextStyle" expandable notifications to make everything readable
        // in the single line case this behaves like the regular one, so no special-casing needed
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setStyle(new Notification.BigTextStyle().bigText(Html.fromHtml(notification.richText, Html.FROM_HTML_MODE_COMPACT)));
        } else {
            builder.setStyle(new Notification.BigTextStyle().bigText(Html.fromHtml(notification.richText)));
        }

        // lock screen visibility
        switch (notification.visibility) {
            case "public":
                builder.setVisibility(Notification.VISIBILITY_PUBLIC);
                break;
            case "private":
                builder.setVisibility(Notification.VISIBILITY_PRIVATE);
                break;
            case "secret":
                builder.setVisibility(Notification.VISIBILITY_SECRET);
                break;
        }

        // grouping
        if (notification.group != null) {
            createGroupNotification(notification);
            builder.setGroup(notification.group);
        }

        // legacy priority handling for versions without NotificationChannel support
        if (Build.VERSION.SDK_INT < 26) {
            switch (notification.urgency) {
                case KNotification.CriticalUrgency:
                    builder.setPriority(Notification.PRIORITY_HIGH);
                    break;
                case KNotification.NormalUrgency:
                    builder.setPriority(Notification.PRIORITY_LOW);
                    break;
                case KNotification.LowUrgency:
                    builder.setPriority(Notification.PRIORITY_MIN);
                    break;
                case KNotification.HighUrgency:
                default:
                    builder.setPriority(Notification.PRIORITY_DEFAULT);
                    break;
            }
        }

        // pending intent flags backward compatibility
        int PENDING_INTENT_FLAG_IMMUTABLE = 0;
        int PENDING_INTENT_FLAG_MUTABLE = 0;
        if (Build.VERSION.SDK_INT >= 23) {
            PENDING_INTENT_FLAG_IMMUTABLE = PendingIntent.FLAG_IMMUTABLE;
        }
        if (Build.VERSION.SDK_INT >= 31) {
            PENDING_INTENT_FLAG_MUTABLE = PendingIntent.FLAG_MUTABLE;
        }

        // taping the notification shows the app
        Intent intent = new Intent(m_ctx.getPackageName() + NOTIFICATION_OPENED);
        intent.putExtra(NOTIFICATION_ID_EXTRA, notification.id);
        PendingIntent contentIntent = PendingIntent.getBroadcast(m_ctx, m_uniquePendingIntentId++, intent, PendingIntent.FLAG_UPDATE_CURRENT | PENDING_INTENT_FLAG_IMMUTABLE);
        builder.setContentIntent(contentIntent);

        // actions
        for (HashMap.Entry<String, String> entry : notification.actions.entrySet()) {
            String id = entry.getKey();
            String label = entry.getValue();

            Intent actionIntent = new Intent(m_ctx.getPackageName() + NOTIFICATION_ACTION);
            actionIntent.putExtra(NOTIFICATION_ID_EXTRA, notification.id);
            actionIntent.putExtra(NOTIFICATION_ACTION_ID_EXTRA, id);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(m_ctx, m_uniquePendingIntentId++, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT | PENDING_INTENT_FLAG_IMMUTABLE);
            Notification.Action action = new Notification.Action.Builder(0, label, pendingIntent).build();
            builder.addAction(action);
        }

        // inline reply actions
        if (notification.inlineReplyLabel != null) {
            Intent replyIntent = new Intent(m_ctx.getPackageName() + NOTIFICATION_REPLIED);
            replyIntent.putExtra(NOTIFICATION_ID_EXTRA, notification.id);
            PendingIntent pendingReplyIntent = PendingIntent.getBroadcast(m_ctx, m_uniquePendingIntentId++, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT | PENDING_INTENT_FLAG_MUTABLE);

            RemoteInput input = new RemoteInput.Builder(REMOTE_INPUT_KEY)
                .setAllowFreeFormInput(true)
                .setLabel(notification.inlineReplyPlaceholder)
                .build();
            Notification.Action replyAction = new Notification.Action.Builder(0, notification.inlineReplyLabel, pendingReplyIntent)
                .addRemoteInput(input)
                .build();
            builder.addAction(replyAction);
        }

        // notification about user closing the notification
        Intent deleteIntent = new Intent(m_ctx.getPackageName() + NOTIFICATION_DELETED);
        deleteIntent.putExtra(NOTIFICATION_ID_EXTRA, notification.id);
        if (notification.group != null) {
            deleteIntent.putExtra(NOTIFICATION_GROUP_EXTRA, notification.group);
        }
        Log.i(TAG, deleteIntent.getExtras() + " " + notification.id);
        builder.setDeleteIntent(PendingIntent.getBroadcast(m_ctx, m_uniquePendingIntentId++, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT | PENDING_INTENT_FLAG_IMMUTABLE));

        m_notificationManager.notify(notification.id, builder.build());
    }

    public void close(int id, String group)
    {
        m_notificationManager.cancel(id);

        if (group != null && m_groupSummaries.containsKey(group)) {
            GroupData g = m_groupSummaries.get(group);
            g.childIds.remove(id);
            if (g.childIds.isEmpty()) {
                m_groupSummaries.remove(group);
                m_notificationManager.cancel(g.groupId);
            } else {
                m_groupSummaries.put(group, g);
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();

        int id = intent.getIntExtra(NOTIFICATION_ID_EXTRA, -1);
        Log.i(TAG, action + ": " + id + " " + intent.getExtras());

        if (action.equals(m_ctx.getPackageName() + NOTIFICATION_ACTION)) {
            // user activated one of the custom actions
            String actionId = intent.getStringExtra(NOTIFICATION_ACTION_ID_EXTRA);
            notificationActionInvoked(id, actionId);
        } else if (action.equals(m_ctx.getPackageName() + NOTIFICATION_DELETED)) {
            // user (or system) dismissed the notification - this can happen both for groups and regular notifications
            String group = null;
            if (intent.hasExtra(NOTIFICATION_GROUP_EXTRA)) {
                group = intent.getStringExtra(NOTIFICATION_GROUP_EXTRA);
            }

            if ((id & NOTIFICATION_GROUP_ID_FLAG) != 0) {
                // entire group has been deleted
                m_groupSummaries.remove(group);
            } else {
                // a single regular notification, so reduce the refcount of the group if there is one
                notificationFinished(id);
                if (group != null && m_groupSummaries.containsKey(group)) {
                    // we do not need to handle the case of childIds being empty here, the system will send us a deletion intent for the group too
                    // this only matters for the logic in close().
                    GroupData g = m_groupSummaries.get(group);
                    g.childIds.remove(id);
                    m_groupSummaries.put(group, g);
                }
            }
        } else if (action.equals(m_ctx.getPackageName() + NOTIFICATION_OPENED)) {
            // user tapped the notification
            Intent newintent = new Intent(m_ctx, m_ctx.getClass());
            newintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            m_ctx.startActivity(newintent);
            notificationActionInvoked(id, "default");
        } else if (action.equals(m_ctx.getPackageName() + NOTIFICATION_REPLIED)) {
            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null) {
                String s = (String) remoteInput.getCharSequence(REMOTE_INPUT_KEY);
                notificationInlineReply(id, s);
            }
        }
    }

    public native void notificationFinished(int notificationId);
    public native void notificationActionInvoked(int notificationId, String action);
    public native void notificationInlineReply(int notificationId, String text);

    private void createGroupNotification(KNotification notification)
    {
        if (m_groupSummaries.containsKey(notification.group)) {
            GroupData group = m_groupSummaries.get(notification.group);
            group.childIds.add(notification.id);
            m_groupSummaries.put(notification.group, group);
            return;
        }

        GroupData group = new GroupData();
        group.childIds.add(notification.id);
        group.groupId = m_uniquePendingIntentId++ + NOTIFICATION_GROUP_ID_FLAG;
        m_groupSummaries.put(notification.channelId, group);

        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= 26) {
            builder = new Notification.Builder(m_ctx, notification.channelId);
        } else {
            builder = new Notification.Builder(m_ctx);
        }

        if (Build.VERSION.SDK_INT >= 23) {
            builder.setSmallIcon((Icon)notification.icon);
        } else {
            builder.setSmallIcon(m_ctx.getApplicationInfo().icon);
        }
        builder.setContentTitle(notification.channelName);
        builder.setContentText(notification.channelDescription);
        builder.setGroup(notification.group);
        builder.setGroupSummary(true);

        // monitor for deletion (which happens when the last child notification is closed)
        int PENDING_INTENT_FLAG_IMMUTABLE = 0;
        if (Build.VERSION.SDK_INT >= 23) {
            PENDING_INTENT_FLAG_IMMUTABLE = PendingIntent.FLAG_IMMUTABLE;
        }

        Intent deleteIntent = new Intent(m_ctx.getPackageName() + NOTIFICATION_DELETED);
        deleteIntent.putExtra(NOTIFICATION_GROUP_EXTRA, notification.group);
        deleteIntent.putExtra(NOTIFICATION_ID_EXTRA, group.groupId);
        builder.setDeleteIntent(PendingIntent.getBroadcast(m_ctx, m_uniquePendingIntentId++, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT | PENDING_INTENT_FLAG_IMMUTABLE));

        // try to stay out of the normal id space for regular notifications
        m_notificationManager.notify(group.groupId, builder.build());
    }
}