我嘗試使用Firebase通知。我能夠通過this文檔正常工作。該消息已收到,我可以從MyFirebaseMessagingService
服務級別向通知欄發送通知。即使應用程序處於後臺或關閉狀態,也會發生此情況。當應用程序處於後臺或關閉狀態時,無法將記錄插入SQLite數據庫中
我需要的是收集通知中發送的數據並將其插入到SQLite數據庫中。我寫的代碼工作正常,如果應用程序在前臺,但它不工作,如果它是關閉或在後臺。這是我爲插入而寫的。
DbHelper dbh=new DbHelper(this,"sample.sqlite",null,1);
SQLiteDatabase sdb=dbh.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("id","1");
cv.put("name","testname");
sdb.insert("test",null,cv);
sdb.close();
dbh.close();
感謝任何幫助。提前致謝。
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.i("Tag","inside message");
Log.i(StaticInfo.INFO, "From: " + remoteMessage.getFrom());
Log.i(StaticInfo.INFO, "Notification Message Title : " + remoteMessage.getNotification().getTitle());
Log.i(StaticInfo.INFO, "Notification Message Body : " + remoteMessage.getNotification().getBody());
insertPromotion();
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
private void insertPromotion()
{
DbHelper dbh = new DbHelper(this, "sample.sqlite", null, 1);
SQLiteDatabase sdb = dbh.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("id","1");
cv.put("name","testname");
sdb.insert("test", null, cv);
sdb.close();
dbh.close();
Log.i("Tag","db closed");
}
}
如果當應用程序是前臺工作的,您的插入代碼完美。如果應用程序在後臺,請檢查它是否正在執行。當應用程序處於後臺時,可能會檢查您的服務正在運行。 –
@SamuelRobert我檢查了它,它從後臺開始工作。當應用程序轉到後臺時,LogCat也會斷開連接。但是我確定服務在任何情況下仍然可以正常顯示。 – Deepak
發佈服務的清單聲明 –