Welcome to mirror list, hosted at ThFree Co, Russian Federation.

NextcloudNotificationManager.java « notification « owncloudnewsreader « luhmer « de « java « main « src « News-Android-App - github.com/nextcloud/news-android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8f71fc8ed2f5e611d423c4b219e6dfda39b774fa (plain)
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
344
345
346
347
348
349
package de.luhmer.owncloudnewsreader.notification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.service.notification.StatusBarNotification;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.media.app.NotificationCompat.MediaStyle;
import androidx.media.session.MediaButtonReceiver;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.luhmer.owncloudnewsreader.BuildConfig;
import de.luhmer.owncloudnewsreader.NewsReaderListActivity;
import de.luhmer.owncloudnewsreader.R;
import de.luhmer.owncloudnewsreader.database.DatabaseConnectionOrm;
import de.luhmer.owncloudnewsreader.database.model.RssItem;
import de.luhmer.owncloudnewsreader.helper.DatabaseUtils;
import de.luhmer.owncloudnewsreader.helper.NotificationActionReceiver;

import static android.app.Notification.EXTRA_NOTIFICATION_ID;
import static de.luhmer.owncloudnewsreader.Constants.NOTIFICATION_ACTION_MARK_ALL_AS_READ_STRING;

public class NextcloudNotificationManager {

    private static final int ID_DownloadSingleImageComplete = 10;
    private static final int UNREAD_RSS_ITEMS_NOTIFICATION_ID = 246;

    public static void showNotificationDownloadSingleImageComplete(Context context, File imagePath) {
        String channelDownloadImage = context.getString(R.string.action_img_download);
        NotificationManager notificationManager = getNotificationManagerAndCreateChannel(context, channelDownloadImage);

        // Load image, decode it to Bitmap and return Bitmap to callback
        ImageSize targetSize = new ImageSize(1024,512); // result Bitmap will be fit to this size
        Bitmap bitmap = ImageLoader.getInstance().loadImageSync("file://" + imagePath.getAbsolutePath(), targetSize);

        // Uri imageUri = Uri.parse(imagePath);
        Uri imageUri = FileProvider.getUriForFile(context,
                BuildConfig.APPLICATION_ID + ".provider",
                imagePath);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(imageUri, "image/*");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);


        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelDownloadImage)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(context.getString(R.string.toast_img_saved))
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));

        notificationManager.notify(ID_DownloadSingleImageComplete, mBuilder.build());
    }



    public static NotificationCompat.Builder buildNotificationDownloadImageService(Context context, String channelId) {
        getNotificationManagerAndCreateChannel(context, channelId);

        Intent intentNewsReader = new Intent(context, NewsReaderListActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intentNewsReader, 0);
        NotificationCompat.Builder mNotificationDownloadImages = new NotificationCompat.Builder(context, channelId)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(context.getString(R.string.notification_download_images_offline))
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
                .setOngoing(true);

        return mNotificationDownloadImages;
    }

    public static void showNotificationSaveSingleCachedImageService(Context context, String channelId, File file) {
        NotificationManager notificationManager = getNotificationManagerAndCreateChannel(context, channelId);

        //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
        //PendingIntent contentIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder mNotificationDownloadImages = new NotificationCompat.Builder(context, channelId)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText("Saved image to: " + file.getPath())
                .setSmallIcon(R.drawable.ic_notification);
                //.setContentIntent(contentIntent);


        notificationManager.notify(1235, mNotificationDownloadImages.build());
    }

    public static NotificationCompat.Builder buildNotificationDownloadWebPageService(Context context, String channelId) {
        getNotificationManagerAndCreateChannel(context, channelId);

        Intent intentNewsReader = new Intent(context, NewsReaderListActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intentNewsReader, 0);
        NotificationCompat.Builder mNotificationWebPages = new NotificationCompat.Builder(context, channelId)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(context.getString(R.string.notification_download_articles_offline))
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
                .setOngoing(true);

        return mNotificationWebPages;
    }



    public static void showNotificationImageDownloadLimitReached(Context context, String channelId, int limit) {
        NotificationManager notificationManager = getNotificationManagerAndCreateChannel(context, channelId);

        Intent intentNewsReader = new Intent(context, NewsReaderListActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intentNewsReader, 0);
        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(context, channelId)
                .setContentTitle("Nextcloud News")
                .setContentText("Only " + limit + " images can be cached at once")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent);

        Notification notify = notifyBuilder.build();

        //Hide the notification after its selected
        notify.flags |= Notification.FLAG_AUTO_CANCEL;

        // Use random ID
        notificationManager.notify(123, notify);
    }

    /**
     * Build a notification using the information from the given media session. Makes heavy use
     * of {@link MediaMetadataCompat#getDescription()} to extract the appropriate information.
     * @param context Context used to construct the notification.
     * @param mediaSession Media session to get information.
     * @return A pre-built notification with information from the given media session.
     */
    public static NotificationCompat.Builder buildPodcastNotification(Context context, String channelId, MediaSessionCompat mediaSession) {
        getNotificationManagerAndCreateChannel(context, channelId);

        /*
        // Creates an explicit intent for an ResultActivity to receive.
        Intent resultIntent = new Intent(context, NewsReaderListActivity.class);
        // Because clicking the notification opens a new ("special") activity, there's
        // no need to create an artificial back stack.
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        context,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        return new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.drawable.ic_notification)
                .setAutoCancel(true)
                .setOngoing(true)
                .setOnlyAlertOnce(true)
                .setContentIntent(resultPendingIntent);
        */

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

        MediaControllerCompat controller = mediaSession.getController();
        MediaMetadataCompat mediaMetadata = controller.getMetadata();
        MediaDescriptionCompat description = mediaMetadata.getDescription();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                /*
                .setStyle(new NotificationCompat.MediaStyle()
                        .setShowActionsInCompactView(
                                new int[]{playPauseButtonPosition})  // show only play/pause in compact view
                        .setMediaSession(mSession.getSessionToken()))
                */
                //.setUsesChronometer(true)
                .setContentTitle(description.getTitle())
                .setContentText(description.getSubtitle())
                .setSubText(description.getDescription())
                .setSmallIcon(R.drawable.ic_notification)
                //.setContentText(description.getSubtitle())
                //.setContentText(mediaMetadata.getText(MediaMetadataCompat.METADATA_KEY_ARTIST))
                //.setSubText(description.getDescription())
                //.setLargeIcon(description.getIconBitmap())
                .setLargeIcon(bitmapIcon)
                .setContentIntent(controller.getSessionActivity())
                .setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP))
                .setOnlyAlertOnce(true);

        boolean isPlaying = controller.getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING;
        builder.addAction(getPlayPauseAction(context, isPlaying));

        // Make the transport controls visible on the lockscreen
        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

        builder.setStyle(new MediaStyle()
            //.setShowActionsInCompactView(0)  // show only play/pause in compact view
            .setMediaSession(mediaSession.getSessionToken())
            .setShowActionsInCompactView(0)
            .setShowCancelButton(true)
            .setCancelButtonIntent(
                    MediaButtonReceiver.buildMediaButtonPendingIntent(
                        context, PlaybackStateCompat.ACTION_STOP)));


        return builder;
    }

    private static NotificationCompat.Action getPlayPauseAction(Context context, boolean isPlaying) {
        int drawableId = isPlaying ? R.drawable.ic_action_pause : R.drawable.ic_action_play;
        String actionText = isPlaying ? "Pause" : "Play"; // TODO extract as string resource

        PendingIntent pendingIntent = MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                isPlaying ? PlaybackStateCompat.ACTION_PAUSE : PlaybackStateCompat.ACTION_PLAY);
        return new NotificationCompat.Action(drawableId, actionText,  pendingIntent);

    }

    public static NotificationCompat.Builder buildDownloadPodcastNotification(Context context, String channelId) {
        getNotificationManagerAndCreateChannel(context, channelId);

        Intent intentNewsReader = new Intent(context, NewsReaderListActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intentNewsReader, 0);
        NotificationCompat.Builder mNotificationDownloadPodcast = new NotificationCompat.Builder(context, channelId)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setContentText(context.getString(R.string.notification_downloading_podcast_title))
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
                .setOngoing(true);

        return mNotificationDownloadPodcast;
    }


    public static void showUnreadRssItemsNotification(Context context, int newItemsCount, SharedPreferences mPrefs) {
        Resources res = context.getResources();
        String tickerMessage = res.getQuantityString(R.plurals.notification_new_items_ticker, newItemsCount, newItemsCount);
        String contentText = res.getQuantityString(R.plurals.notification_new_items_text, newItemsCount, newItemsCount);

        String channelId = context.getString(R.string.app_name);
        NotificationManager notificationManager = getNotificationManagerAndCreateChannel(context, channelId);

        DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(context);
        DatabaseConnectionOrm.SORT_DIRECTION sortDirection = DatabaseUtils.getSortDirectionFromSettings(mPrefs);
        List<RssItem> items = dbConn.getAllUnreadRssItemsForNotification(sortDirection);

        List<String> previewLines = new ArrayList<>();
        for (RssItem item : items) {
            // • = \u2022,   ● = \u25CF,   ○ = \u25CB,   ▪ = \u25AA,   ■ = \u25A0,   □ = \u25A1,   ► = \u25BA
            previewLines.add("\u2022 " + item.getTitle().trim());
        }
        String previewText = TextUtils.join("\n", previewLines);

        Intent markAllAsReadIntent = new Intent(context, NotificationActionReceiver.class);
        markAllAsReadIntent.setAction(NOTIFICATION_ACTION_MARK_ALL_AS_READ_STRING);
        markAllAsReadIntent.putExtra(EXTRA_NOTIFICATION_ID, UNREAD_RSS_ITEMS_NOTIFICATION_ID);
        PendingIntent markAllAsReadPendingIntent = PendingIntent.getBroadcast(context, 0, markAllAsReadIntent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context, channelId)
                        .setSmallIcon(R.drawable.ic_notification)
                        .setContentTitle(tickerMessage)
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(previewText))
                        //.setDefaults(Notification.DEFAULT_ALL)
                        .addAction(R.drawable.ic_checkbox_white, context.getString(R.string.menu_markAllAsRead), markAllAsReadPendingIntent)
                        .setAutoCancel(true)
                        .setNumber(newItemsCount)
                        .setContentText(contentText);


        Intent notificationIntent = new Intent(context, NewsReaderListActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, UNREAD_RSS_ITEMS_NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        notificationManager.notify(UNREAD_RSS_ITEMS_NOTIFICATION_ID, builder.build());
    }

    public static boolean isUnreadRssCountNotificationVisible(Context context) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for(StatusBarNotification statusBarNotification : notificationManager.getActiveNotifications()) {
                if(statusBarNotification.getId() == UNREAD_RSS_ITEMS_NOTIFICATION_ID) {
                    return true;
                }
            }
        }
        return false;

    }

    public static void removeRssItemsNotification(Context context) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(UNREAD_RSS_ITEMS_NOTIFICATION_ID);
    }














    private static NotificationManager getNotificationManagerAndCreateChannel(Context context, String channelId) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel mChannel = new NotificationChannel(channelId, channelId, importance);
            mChannel.setSound(null, null);
            mChannel.enableVibration(false);
            //mChannel.setShowBadge(false);
            //mChannel.enableLights(true);
            notificationManager.createNotificationChannel(mChannel);
        }
        return notificationManager;
    }

}