Как сохранить получение уведомлений от push-уведомлений Firebase в приложении для будущих целей? - PullRequest
0 голосов
/ 01 июля 2019

Я должен сохранить уведомления для будущих целей в моем приложении для Android. Я гуглю и смотрю видео на YouTube, но не смог решить мою проблему. Поэтому я прошу дать несколько советов, чтобы решить эту проблему !!!

1 Ответ

0 голосов
/ 02 июля 2019

Вы можете хранить уведомления в локальной базе данных, используя SQLite.

В основном вы можете сделать следующее:

Создание помощника для создания таблицы в базе данных SQLite:

 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseHelper extends SQLiteOpenHelper {

  //Database Name
  private static final String DATABASE = "myDatabaseName";

  //Database Version
  public static int VERSION = 1;

  //Database tables
  private static final String TABLE_NOTIFICATIONS = "notifications";

  //Notification fields
  private static final String KEY_ID = "id";

  //Notifications Table
  private static final String KEY_DESCRIPTION = "description";

  public DatabaseHelper(Context context){
    super(context, DATABASE, null, VERSAO);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {

    String CREATE_NOTIFICATIONS_TABLE = "CREATE TABLE " + TABLE_NOTIFICATIONS + "(" +
            KEY_ID + " INTEGER PRIMARY KEY, "
            + KEY_DESCRIPTION + " VARCHAR(255) "
            +");";

    db.execSQL(CREATE_NOTIFICATIONS_TABLE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTIFICATIONS);

    onCreate(db);
  }
}

Создайте для него боб:

       public class NotificationBean {

          private String description;

          public String getDescription() {
            return description;
          }

          public void setDescription(String description) {
            this.description = description;
          }
      }

Я также рекомендую создать DAO для всего процесса:

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;

    import com.yourpackage.beans.NotificationBean;
    import com.yourpackage.helpers.DatabaseHelper;

    import java.util.ArrayList;
    import java.util.List;

    public class NotificationDao {

        private DatabaseHelper helper;
        private SQLiteDatabase database;
        private ContentValues contentValues;

        public NotificationDao(Context context){
            helper = new DatabaseHelper(context);
        }

        private SQLiteDatabase getDatabase(){
            if(database == null){
                database = helper.getWritableDatabase();
            }
            return database;
        }
        public void close(){
            helper.close();
        }

        public void addNotification(NotificationBean notificationBean){
            contentValues = new ContentValues();
            contentValues.put("description", notificationBean.getDescription());
            getDatabase().insert("notifications", null, contentValues);
        }

        public List<NotificationBean> getNotifications(){
            List<NotificationBean> notificationBeanList = new ArrayList<>();
            final String SELECT_QUERY = "SELECT description FROM notifications";
            Cursor cursor = getDatabase().rawQuery(SELECT_QUERY, null);

            if(cursor.moveToFirst()){
                do{
                    NotificationBean notificationBean = new NotificationBean();
                    notificationBean.setDescription(cursor.getString(0));
                    notificationBeanList.add(notificationBean);
                }while (cursor.moveToNext());
            }
            return notificationBeanList;
        }
    }

Как только вы создали это, вам просто нужно позвонить в службу уведомлений

public class NotificationsListenerService extends FirebaseMessagingService {

private NotificationDao notificationDao;
private NotificationBean notificationBean;

@Override
public void onMessageReceived(RemoteMessage message) {

    //Saving notification on database

    notificationDao = new NotificationDao(NotificationsListenerService.this);
    notificationBean = new NotificationBean();
    notificationBean.setDescription(message.getNotification().getBody());
    notificationDao.addNotification(notificationBean);
 }
}

Имейте в виду, что вы можете добавить любые поля, которые вы хотите для своей таблицы, это просто я использую в некоторых проектах. Но вы также можете добавить поле create_at, чтобы отслеживать даты добавления уведомлений.

Вот и все, если у вас есть другие вопросы, просто дайте мне знать

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...