2017-02-27 23 views
0

我想將所有在服務的onMessageReceived中接收到的消息保存在SQLite數據庫中。FirebaseMessagingService是一個意向服務嗎?

我正打算打開數據庫,插入數據和關閉數據庫。這對於意圖服務來說可以很好地工作,因爲所有對onMessageReceived的調用都將排隊並因此逐一執行。

但是,如果onMessageReceived獲取多個消息同時調用,可能會導致,而另一個呼叫試圖寫入從而導致問題被關閉數據庫的問題。

任何人都可以證實我應該期待什麼樣的行爲。

如果不是意圖的服務,我可能要看看DB Singleton模式和同步塊

+0

你檢查出火力的離線使用? –

+0

這是一個服務......但是它同時收到消息嗎?從我所看到的多個消息逐一接收。但我不確定它是否會一直如此。 – Kushan

+0

@JadavLalit我不認爲firebase db的持久性會幫助我使用FCM。那是你所指的? – Kushan

回答

0

您可以檢查LinkedBlockingDeque<>類隊列中的請求,可以在後臺按順序進行。
檢查下面的示例類礦井 -

public class Processor implements Runnable { 

private final LinkedBlockingDeque<Task> mTaskQueue = new LinkedBlockingDeque<Task>(); 
private boolean mExecuteTask = true; 

@Override 
public void run() { 
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 
    // You can put some end condition if needed 
    while (mExecuteTask) { 
     Task task; 
     try { 
      // Waits if necessary until an element becomes available 
      task = (Task) mTaskQueue.take(); 
     } catch (InterruptedException e) { 
      continue; // re-test the condition on the eclosing while 
     } 
     if (task != null) { 
      task.runnable.run(); 
     } 
    } 
} 

// Call this method to put Runnable in Queue. 
public synchronized void put(int id, Runnable runnable) { 
    try { 
     Task task = new Task(); 
     task.runnable = runnable; 
     task.id = id; // someUniqueId to avoid duplication 
     // Check Id of tasks already present in Queue 
     mTaskQueue.addLast(task); 
    } catch (IllegalStateException ie) { 
     throw new Error(ie); 
    } 
} 

private static class Task { 
    public Runnable runnable; 
    // Unique Id of task 
    public int id; 
} 

}

相關問題