Recommand · June 5, 2021 0

Toggle user specific notifications for android

I send notifications to users via a server. "Firebase FCM Notification" I send notifications according to the data they add. I want it to stop notifications when users want it. I tried many methods for this, but I couldn’t find a solution. Users already determine the content of the sent notification. How do I get them to just turn them off whenever they want?

Regards.

@SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class WOnTrackerFirebaseMessagingService extends FirebaseMessagingService{
    protected Context mContext;
    Context context;
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            if (isUserLoggedIn()) {
               sendNotification(remoteMessage.getData());
            }
        }
    }

    private void sendRegistrationToServer(String token) {
    }

    private void sendNotification(Map<String, String> data) {

        if(!isUserLoggedIn()) return;

        long diff = Utils.getCurrentMili() - getPremiumTime();
        if (diff >= 0) {
            return;
        }
        if(!isNotifyEnabled()){
            return;
        }

        String strPhone = data.get("phone");

        try {
            if(strPhone.length() > 9){
                int start = strPhone.length()- 9;
                strPhone = strPhone.substring(start);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        int notificationId = Utils.getIntFromString(strPhone);
        if(notificationId == 0) {
            notificationId = new Random().nextInt(60000);//send now

        }
        String strName = data.get("phonereverse");

        try {
            if(strName.length() > 9){
                int start = strName.length()- 9;
                strName = strName.substring(start);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        int notificationIda = Utils.getIntFromString(strName);
        if(notificationIda == 0) {
            notificationIda = new Random().nextInt(60000);//send now

        }
            PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationId, intent,
                    PendingIntent.FLAG_ONE_SHOT);
            String channelIds = getString(R.string.default_notification_channel_id); // Offline
            String channelId = getString(R.string.default_notification_channel_ids); // Online

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            String messageTitle = null;

            String type = data.get("type");
            String saat = "";
            String onlineSaat = "";
            String messageBody = "";

            if (type != null && type.equals("PERIOD")) {
                messageBody += "";

                Double days = Double.parseDouble(data.get("days"));
                Double hours = Double.parseDouble(data.get("hours"));
                Double minutes = Double.parseDouble(data.get("minutes"));
                Double seconds = Double.parseDouble(data.get("seconds"));
                String dateStr = data.get("date") + " " + data.get("unavailableTime");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-dd-mm HH:mm:ss", Locale.ENGLISH);
                df.setTimeZone(TimeZone.getTimeZone("GMT+3"));
                Date date = null;
                try {
                    date = df.parse(dateStr);
                    df.setTimeZone(TimeZone.getDefault());
                    String formattedDate = df.format(date);
                    String[] strParts = formattedDate.split(" ");
                    saat = strParts[1];

                } catch (ParseException e) {
                    // e.printStackTrace();
                }


                if (days > 0) {
                    messageBody += days.intValue() + " days and ";
                }

                if (hours > 0) {
                    messageBody += hours.intValue() + getString(R.string.hours) + " ";
                }

                if (minutes > 0) {
                    messageBody += "" + minutes.intValue() + " " + getString(R.string.minute) + " ";
                }

                messageBody += seconds.intValue() + " " + getString(R.string.seconds) + " " + getString(R.string.firebase_messaging_service_page_online_message) + " (" + saat + ")";
                messageTitle = getString(R.string.notification_title);

                Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.logo_image);
                NotificationCompat.Builder notificationBuilder =
                        new NotificationCompat.Builder(this, channelIds)
                                .setSmallIcon(R.drawable.logo_image)
                                .setContentText(messageBody)
                                .setLargeIcon(largeIcon)
                                .setSound(defaultSoundUri)
                                .setContentTitle(data.get("name") + " " + messageTitle)
                                .setAutoCancel(true)
                                .setContentIntent(pendingIntent);

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

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channels = new NotificationChannel(channelIds,
                            getResources().getString(R.string.notification_channel_title),
                            NotificationManager.IMPORTANCE_DEFAULT);

                    notificationManager.createNotificationChannel(channels);
                }

                notificationManager.notify(notificationId, notificationBuilder.build());

            } else if (type != null && type.equals("ONLINE")) {
                String dateOnlineNow = data.get("date");
                SimpleDateFormat dfOnline = new SimpleDateFormat("yyyy-dd-mm HH:mm:ss", Locale.ENGLISH);
                dfOnline.setTimeZone(TimeZone.getTimeZone("GMT+3"));
                Date dates = null;
                try {
                    dates = dfOnline.parse(dateOnlineNow);
                    dfOnline.setTimeZone(TimeZone.getDefault());
                    String formattedDate = dfOnline.format(dates);
                    String[] strPartsO = formattedDate.split(" ");
                    onlineSaat = strPartsO[1];

                } catch (ParseException e) {
                    // e.printStackTrace();
                }
                messageBody += getString(R.string.notification_online) + " (" + onlineSaat + ")";
                messageTitle = getString(R.string.notification_online);

                Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.logo_image);
                NotificationCompat.Builder notificationBuilder =
                        new NotificationCompat.Builder(this, channelId)
                                .setSmallIcon(R.drawable.logo_image)
                                .setContentText(messageBody)
                                .setLargeIcon(largeIcon)
                                .setSound(defaultSoundUri)
                                .setContentTitle(data.get("name") + " " + messageTitle)
                                .setAutoCancel(true)
                                .setContentIntent(pendingIntent);

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

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel(channelId,
                            getResources().getString(R.string.notification_channel_titles),
                            NotificationManager.IMPORTANCE_DEFAULT);

                    notificationManager.createNotificationChannel(channel);
                }

                notificationManager.notify(notificationIda, notificationBuilder.build());
            }
    }

    protected boolean isUserLoggedIn() {

        SharedPreferences preferences =  this.getSharedPreferences(BaseActivity.SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);

        return preferences.getBoolean("isLoggedIn",false);

    }
    protected boolean isNotifyEnabled() {

        SharedPreferences preferences =  this.getSharedPreferences(Constants.SHARED_PREFERENCE, 0);

        return preferences.getBoolean(Constants.MSG_NOTIFY,true);

    }
    protected  long getPremiumTime(){
        SharedPreferences preferences =  this.getSharedPreferences(Constants.SHARED_PREFERENCE, 0);

        return preferences.getLong(Constants.PREMIUM_TIME,0);
    }
}