android聊天应用程序中用户列表视图中的新消息通知

时间:2015-03-10 11:15:57

标签: android parsing

您好我正在开发一个使用parse作为后端和sinch服务的Android聊天应用程序。 一切都很好,就像在两个Android设备之间发送和接收消息一样。我也使用来自parse.com的推送通知。 现在我想修改应用程序,比如新消息到达时它必须显示消息在我的聊天应用程序中是等待的 最新应用内

这是我的代码

ListUserActivity.java

    private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereNotEqualTo("objectId", currentUserId);
    query.findInBackground(new FindCallback<ParseUser>() {
        public void done(List<ParseUser> userList, com.parse.ParseException    e) {
            if (e == null) {
                for (int i=0; i<userList.size(); i++) {
                    names.add(userList.get(i).getUsername().toString());
                }
                usersListView = (ListView)findViewById(R.id.usersListView);
                namesArrayAdapter =
                        new ArrayAdapter<String>(getApplicationContext(),
                                R.layout.user_list_item, names);
                usersListView.setAdapter(namesArrayAdapter);

                usersListView.setOnItemClickListener(new    AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> a, View v, int i,   long l) {
                        try {
                            System.out.println(i);
                            openConversation(names, i);
                        }
                        catch (IndexOutOfBoundsException e1){
                            System.out.println(e1.getMessage());
                        }
                    }
                });
            } else {
                Toast.makeText(getApplicationContext(),
                        "Error loading user list",
                        Toast.LENGTH_LONG).show();
            }
        }
    });
  }

MessagingActivity.java

public class MessagingActivity extends ActionBarActivity {

private String recipientId;
private String name;
private EditText messageBodyField;
private String messageBody;
private MessageService.MessageServiceInterface messageService;
private MessageAdapter messageAdapter;
private ListView messagesList;
private String currentUserId;
private ServiceConnection serviceConnection = new MyServiceConnection();
private MessageClientListener messageClientListener = new MyMessageClientListener();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.messaging);

    bindService(new Intent(this, MessageService.class), serviceConnection,   BIND_AUTO_CREATE);

    Intent intent = getIntent();
    recipientId = intent.getStringExtra("RECIPIENT_ID");
    name=intent.getStringExtra("name");
    setTitle(name);
    currentUserId = ParseUser.getCurrentUser().getObjectId();

    // Store app language and version
    ParseInstallation installation =   ParseInstallation.getCurrentInstallation();
    installation.put("userI", currentUserId);
    installation.saveInBackground();

    messagesList = (ListView) findViewById(R.id.listMessages);
    messageAdapter = new MessageAdapter(this);
    messagesList.setAdapter(messageAdapter);
    populateMessageHistory();

    messageBodyField = (EditText) findViewById(R.id.messageBodyField);

    findViewById(R.id.sendButton).setOnClickListener(new   View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
        }
    });
}

//get previous messages from parse & display
private void populateMessageHistory() {
    String[] userIds = {currentUserId, recipientId};
    ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage") ;
    query.whereContainedIn("senderId", Arrays.asList(userIds));
    query.whereContainedIn("recipientId", Arrays.asList(userIds));
    query.orderByAscending("createdAt");
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> messageList,   com.parse.ParseException e) {
            if (e == null) {
                for (int i = 0; i < messageList.size(); i++) {
                    WritableMessage message = new    WritableMessage(messageList.get(i).get("recipientId").toString(),  messageList.get(i).get("messageText").toString());
                    if  (messageList.get(i).get("senderId").toString().equals(currentUserId)) {
                        messageAdapter.addMessage(message,   MessageAdapter.DIRECTION_OUTGOING);
                    } else {
                        messageAdapter.addMessage(message,  MessageAdapter.DIRECTION_INCOMING);
                    }
                }
            }
        }
    });
}

private void sendMessage() {
    messageBody = messageBodyField.getText().toString();
    if (messageBody.isEmpty()) {
        Toast.makeText(this, "Please enter a message", Toast.LENGTH_LONG).show();
        return;
    }
    messageService.sendMessage(recipientId, messageBody);
    messageBodyField.setText("");
}

@Override
public void onDestroy() {
    messageService.removeMessageClientListener(messageClientListener);
    unbindService(serviceConnection);
    super.onDestroy();
}

private class MyServiceConnection implements ServiceConnection {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        messageService = (MessageService.MessageServiceInterface) iBinder;
        messageService.addMessageClientListener(messageClientListener);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        messageService = null;
    }
}
private class MyMessageClientListener implements MessageClientListener {
    @Override
    public void onMessageFailed(MessageClient client, Message message,
                                MessageFailureInfo failureInfo) {
        Toast.makeText(MessagingActivity.this, "Message failed to send.",    Toast.LENGTH_LONG).show();
    }


    @Override
    public void onIncomingMessage(MessageClient client, Message message) {
        if (message.getSenderId().equals(recipientId)) {
           //   Toast.makeText(getApplicationContext(),"message",Toast.LENGTH_SHORT).show();
            WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
            messageAdapter.addMessage(writableMessage,  MessageAdapter.DIRECTION_INCOMING);
        }

    }

    @Override
    public void onMessageSent(MessageClient client, Message message, final String recipientId) {

        final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
        messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
        //only add message to parse database if it doesn't already exist there
       ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
        query.whereEqualTo("sinchId", message.getMessageId());
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> messageList, com.parse.ParseException e) {
                if (e == null) {

                    if (messageList.size() == 0) {
                        ParseObject parseMessage = new ParseObject("ParseMessage");
                        parseMessage.put("senderId", currentUserId);
                        parseMessage.put("recipientId", writableMessage.getRecipientIds().get(0));
                        parseMessage.put("messageText", writableMessage.getTextBody());
                        parseMessage.put("sinchId", writableMessage.getMessageId());
                        parseMessage.put("read",false);
                        parseMessage.saveInBackground();
                        //  messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);

                        ParseUser user = ParseUser.getCurrentUser();
                        String name = user.getUsername();
                       // Create our Installation query
                        ParseQuery pushQuery = ParseInstallation.getQuery();
                        pushQuery.whereEqualTo("userI", writableMessage.getRecipientIds().get(0));

                        // Send push notification to query
                        ParsePush push = new ParsePush();
                        push.setQuery(pushQuery); // Set our Installation query
                        push.setMessage("Message from"+ name +writableMessage.getTextBody());
                        push.sendInBackground();

                    }
                }
            }
        });
    }

    @Override
    public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {
            Toast.makeText(getApplicationContext(),"delivered",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onShouldSendPushData(MessageClient client, Message message,    List<PushPair> pushPairs) {}
}

}

1 个答案:

答案 0 :(得分:0)

您可以向数据库添加新列,以跟踪对话是否包含未读消息。每当有新消息到达时,您可以通过将此列设置为true将对话标记为未读或待处理。 构建列表时,如果对话具有未读消息,请使适配器检查此列并更新生成的列表视图。 当用户打开对话时,将列更新为false。

首先,我建议您使用带有CursorLoader的ListView: http://developer.android.com/guide/topics/ui/layout/listview.html

每当您的内容提供商发生变化时,都会通知您的适配器。当它循环遍历构建每个列表项View的光标时,检查所需的列。如果已设置,则在该视图上设置您喜欢的任何内容,以表明它未读。