Как создать страницу настроек уведомлений в приложении для Android с помощью Onesignal Notification?

Я хочу создать страницу настроек уведомлений в приложении для Android, чтобы пользователь мог выбрать, какой тип уведомлений он хочет. Я использую службу push-уведомлений OneSignal и отправляю уведомление из панели OneSignal Dashboard.

Я создал группу/категории в Onesignal Dashboard, которая показывает только Android Oreo и более поздние версии. Вот почему мне нужна страница настройки уведомлений внутри приложения, чтобы любая версия пользователя Android могла использовать эти функции.

У меня есть только один класс Java для одного уведомления о сигнале с именем ExampleApplication.java, взятого из GitHub.

package com.myapp.demo;
import android.app.Application;
import android.content.Intent;
import android.util.Log;

import com.crashlytics.android.Crashlytics;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;

import io.fabric.sdk.android.Fabric;
import org.json.JSONObject;

public class ExampleApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Fabric.with(this, new Crashlytics());

        // Logging set to help debug issues, remove before releasing your app.

        OneSignal.startInit(this)
                .setNotificationReceivedHandler(new ExampleNotificationReceivedHandler())
                .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();
        OneSignal.enableVibrate(false);

    }


    private class ExampleNotificationReceivedHandler implements OneSignal.NotificationReceivedHandler {
        @Override
        public void notificationReceived(OSNotification notification) {

            JSONObject data = notification.payload.additionalData;
            String notificationID = notification.payload.notificationID;

            String customKey;
            Log.i("OneSignalExample", "NotificationID received: " + notificationID);

            if (data != null) {
                customKey = data.optString("customkey", null);
                if (customKey != null)
                    Log.i("OneSignalExample", "customkey set with value: " + customKey);
            }
        }
    }

    private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
        // This fires when a notification is opened by tapping on it.
        @Override
        public void notificationOpened(OSNotificationOpenResult result) {
            OSNotificationAction.ActionType actionType = result.action.type;
            JSONObject data = result.notification.payload.additionalData;

            String customKey;
            String openURL = null;
            Object activityToLaunch = MainActivity.class;

            if (data != null) {
                customKey = data.optString("customkey", null);
                openURL = data.optString("openURL", null);

                if (customKey != null)
                    Log.i("OneSignalExample", "customkey set with value: " + customKey);

                if (openURL != null)
                    Log.i("OneSignalExample", "openURL to webview with URL value: " + openURL);
            }

            if (actionType == OSNotificationAction.ActionType.ActionTaken) {
                Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

                if (result.action.actionID.equals("id1")) {
                    Log.i("OneSignalExample", "button id called: " + result.action.actionID);
                    activityToLaunch = MainActivity.class;
                } else
                    Log.i("OneSignalExample", "button id called: " + result.action.actionID);
            }
            // The following can be used to open an Activity of your choice.
            // Replace - getApplicationContext() - with any Android Context.
            // Intent intent = new Intent(getApplicationContext(), YourActivity.class);
            Intent intent = new Intent(getApplicationContext(), (Class<?>) activityToLaunch);

            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);

            // close app clearing all task
            //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);

            intent.putExtra("openURL", openURL);
            Log.i("OneSignalExample", "openURL = " + openURL);
            startActivity(intent);
        }
    }
}

Я хочу создать страницу настроек, подобную этой.

введите здесь описание изображения

Как я могу создать эту страницу настройки уведомлений?


person user3137451    schedule 20.01.2020    source источник


Ответы (1)


введите здесь описание изображения

Настройки.java

attendanceSwitch = findViewById(R.id.attendance_switch);
        noticeSwitch = findViewById(R.id.notice_switch);
        hwSwitch = findViewById(R.id.hw_switch);
        testSwitch = findViewById(R.id.test_switch);
        busSwitch = findViewById(R.id.bus_switch);
        settingsFeedback = findViewById(R.id.settings_feedback);

        if (sharedPreferences.getBoolean("animate", false)){ reduceAnimation.setChecked(true); } else { reduceAnimation.setChecked(false); }

        reduceAnimation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()){
                    editor.putBoolean("animate" , true);
                } else {
                    editor.putBoolean("animate" , false);
                }
                editor.apply();
            }
        });

////////////////
        if (sharedPreferences.getBoolean("attendanceSwitch", true)){ attendanceSwitch.setChecked(true); } else { attendanceSwitch.setChecked(false); }

        attendanceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()){
                    editor.putBoolean("attendanceSwitch" , true);
                } else {
                    editor.putBoolean("attendanceSwitch" , false);
                }
                editor.apply();
            }
        });
////////////////////////

        if (sharedPreferences.getBoolean("noticeSwitch", true)){ noticeSwitch.setChecked(true); } else { noticeSwitch.setChecked(false); }

        noticeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()){
                    editor.putBoolean("noticeSwitch" , true);
                } else {
                    editor.putBoolean("noticeSwitch" , false);
                }
                editor.apply();
            }
        });
///////////////////////

        if (sharedPreferences.getBoolean("hwSwitch", true)){ hwSwitch.setChecked(true); } else { hwSwitch.setChecked(false); }

        hwSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()){
                    editor.putBoolean("hwSwitch" , true);
                } else {
                    editor.putBoolean("hwSwitch" , false);
                }
                editor.apply();
            }
        });

//////////////////////////

        if (sharedPreferences.getBoolean("testSwitch", true)){ testSwitch.setChecked(true); } else { testSwitch.setChecked(false); }

        testSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()){
                    editor.putBoolean("testSwitch" , true);
                } else {
                    editor.putBoolean("testSwitch" , false);
                }
                editor.apply();
            }
        });

 //////////////////////////

        if (sharedPreferences.getBoolean("busSwitch", true)){ busSwitch.setChecked(true); } else { busSwitch.setChecked(false); }

        busSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()){
                    editor.putBoolean("busSwitch" , true);
                } else {
                    editor.putBoolean("busSwitch" , false);
                }
                editor.apply();
            }
        });

NotificationService.java

if (channelid.equals("Attendance")){

            if (sharedPreferences.getBoolean("attendanceSwitch", true)){

                NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelid);
                builder.setSmallIcon(R.mipmap.ic_logo);
                builder.setContentTitle(title);
                builder.setContentText("Marked "+ attendance);
                builder.setPriority(pri);
                NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
                notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());

            }

        } else if (channelid.equals("test")){

            if (sharedPreferences.getBoolean("testSwitch", true)) {

                PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                        new Intent(this, PreQuiz.class), PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelid);
                builder.setSmallIcon(R.mipmap.ic_logo);
                builder.setContentTitle(title);
                builder.setContentText(body);
                builder.setPriority(pri);
                builder.setContentIntent(contentIntent);
                NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
                notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());

            }

        } else if (channelid.equals("notice")){

            if (sharedPreferences.getBoolean("noticeSwitch", true)) {


                PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, Noticeboard.class), PendingIntent.FLAG_UPDATE_CURRENT);

            if (section.equals(sharedPreferences.getString("Section", "...")) || section.equals("All")) {
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelid);
                builder.setSmallIcon(R.mipmap.ic_logo);
                builder.setContentTitle(title);
                builder.setContentText(body);
                builder.setPriority(pri);
                builder.setContentIntent(contentIntent);
                // builder.addAction(R.drawable.ic_add_black_24dp, "Sdad", snoozePendingIntent);
                NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
                notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());

            }
            }

        } else if (channelid.equals("hw")){

            if (sharedPreferences.getBoolean("hwSwitch", true)) {


                PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                        new Intent(this, Homework.class), PendingIntent.FLAG_UPDATE_CURRENT);

                if (section.equals(sharedPreferences.getString("Section", "...")) || section.equals("All")) {
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelid);
                    builder.setSmallIcon(R.mipmap.ic_logo);
                    builder.setContentTitle(title);
                    builder.setContentText(body);
                    builder.setContentIntent(contentIntent);
                    builder.setPriority(pri);
                    // builder.addAction(R.drawable.ic_add_black_24dp, "Sdad", snoozePendingIntent);
                    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
                    notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());
                }
            }
person Gnana Sreekar    schedule 24.05.2020