通过推送通知接收消息唤醒并在后台发送传递

时间:2014-12-22 00:07:37

标签: android quickblox

使用 quickblox API,在应用处于后台时接收消息(接收推送通知后)的正确策略是什么?

这是我的方法(但它无法正常工作): 在GCMIntentService中收到推送通知后,我正在使用QBChatService登录(创建会话和用户登录后)。 然后使用QBChatService.getDialogMessages()我检索消息并保存在数据库中。最后,我从聊天服务注销并销毁它。

重点是应用程序进入后台并按预期接收消息。但是当它再次出现前景时,它不再接收消息。 如果我评论updateDialog(dialogId)(请参阅下面的代码段),这意味着在推送通知后在后台没有消息检索,那么一切都按预期工作。 注意:每当应用程序进入后台时,它都会注销,当到达前台时会再次登录。

似乎问题是使用QBChatService方法中的loadDialogMessages登录。

我使用Quickblox 2.0 api和Q-municate作为我的基本代码。 Q-municate中的实现是这样的:当应用程序进入后台(并注销)时,它只是通知用户一条新消息。如果用户将应用程序带到前台,则应用程序将检索新消息。但我希望在用户将应用程序带到前台之前检索消息(在收到推送通知后)并在本地保存。

知道如何解决这个问题吗?

以下是我使用的代码的一部分:

//GCMIntentService.java

protected void onHandleIntent(Intent intent) {
    ...
    if(isAppRunning()) {
        // ignore
    }else{
        updateDialog(dialogId); //Retrieves messages synchronously from server, saves in data base and sends delivery notice
        sendNotification(); // notifies user 
    }
    ...
}

public void updateDialog(String dialogId)
        throws BaseServiceException, SmackException, XMPPException, IOException {
    QBDialog dialog = DatabaseManager.getDialogByDialogId(context, dialogId);

    MessageCache lastMessage = DatabaseManager.getLastMessage(context, dialog);
    if (lastMessage == null) {
        loadDialogMessages(dialog, 0L);
    } else {
        long lastMessageDateSent = lastMessage.getTime();
        loadDialogMessages(dialog, lastMessageDateSent);
    }
}

public void  loadDialogMessages(QBDialog dialog, long lastDateLoad)
        throws IOException, BaseServiceException, XMPPException, SmackException {
    if(!QBChatService.isInitialized()) {
        QBChatService.init(context);
    }
    QBChatService chatService = QBChatService.getInstance();
    if(!chatService.isLoggedIn()) {
        chatService.login(login()); // login() method creates session and signes in the user
    }
    chatService.stopAutoSendPresence();

    if (lastDateLoad != 0L) {
        Bundle bundle = new Bundle();
        QBCustomObjectRequestBuilder customObjectRequestBuilder = new QBCustomObjectRequestBuilder();
        customObjectRequestBuilder.setPagesLimit(Consts.DIALOG_MESSAGES_PER_PAGE);
        customObjectRequestBuilder.gt(com.quickblox.internal.module.chat.Consts.MESSAGE_DATE_SENT,
                lastDateLoad);
        List<QBChatHistoryMessage> dialogMessagesList = QBChatService.getDialogMessages(dialog, customObjectRequestBuilder, bundle);

        if (dialogMessagesList != null) {
            saveChatMessagesAndSendDelivery(chatService, dialogMessagesList, dialog.getDialogId());
        }
    }

    chatService.logout();
    chatService.destroy();
}    

0 个答案:

没有答案
相关问题