SQLite不存储所有数据

时间:2016-12-05 23:53:40

标签: android sqlite firebase android-notifications firebase-cloud-messaging

我想要做的是,当我向我的Android应用程序发送通知(使用Firebase)时,我将通知消息存储在SQLite表中,让用户在ListView中查看他的通知。

问题是SQLite仅在应用程序位于前台时存储通知文本,否则手机会收到通知,但不保存通知。

我在类中创建数据库:DBController

    my_dict[word] = number
return {k:v for k, v in my_dict.items() if v > i} 

我如何存储通知消息:

public DBContoller(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, "cloudmessaging.db", factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE Messages(MSG TEXT,created_at DATETIME DEFAULT CURRENT_TIMESTAMP);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS Messages");
}
ContentValues cv;
//add
public void add(String MSG){
    cv=new ContentValues();
    cv.put("MSG",MSG);
    this.getWritableDatabase().insertOrThrow("Messages", "", cv);
}
public void selectAll(List lst){
    Cursor cursor= this.getReadableDatabase().rawQuery("SELECT * FROM Messages order by created_at DESC ",null);
    lst.clear();
    while(cursor.moveToNext()){
        lst.add("Message : "+cursor.getString(0)+" - ["+cursor.getString(1)+" ]");
    }
}

我如何显示存储的消息:

NotificationCompat.Builder notifBuilder=new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Gi2017 :)")
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(notifsound)
            .setContentIntent(pendingintent);

    NotificationManager notifManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notifManager.notify(0/*notification ID*/,notifBuilder.build());

    try{
        DBContoller db=new DBContoller(getApplicationContext(),"",null,1);
        db.add(body);
    }catch(Exception e){Log.d("error DB",e.getMessage());}

2 个答案:

答案 0 :(得分:0)

您最有可能发送通知消息。正如documentation for Firebase Cloud Messaging所述,当应用程序背景时,系统会处理通知消息:

  

当您希望FCM处理代表您的客户端应用程序显示通知时,请使用通知消息。如果要在客户端应用程序上处理消息,请使用数据消息。

如果您始终希望自己的应用代码获取消息,则应发送data message

答案 1 :(得分:0)

    You can create table like this.


final String NOTIFICATION_SAVE = "CREATE TABLE " + NOTIFICATION_GROUPING + "(" + ROW_ID + " INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL UNIQUE," + FEED_ID + " TEXT," + MESSAGE + " TEXT," + ACTION + " TEXT)";
        db.execSQL(NOTIFICATION_SAVE);


    And store data into created table like this.

SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(FEED_ID , "102");
        cv.put(MESSAGE, "notification");
        db.insert(NOTIFICATION_GROUPING, null, cv);
        db.close();