消息无法发送

时间:2014-10-10 08:13:57

标签: java android android-layout android-activity parse-platform

我正在使用Sinch和Parse,在MessagingActivity上我也收到以下消息:消息无法发送(在onMessageFailed方法中)。我试图理解为什么消息未能注册到Parse:,并一起发送

以下是我认为触发错误的活动:

public class MessagingActivity1 extends Activity {
    private String recipientId;
    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);

        Parse.initialize(this, "Code", "Code");

        bindService(new Intent(this, MessageService.class), serviceConnection,
                BIND_AUTO_CREATE);
        Intent intent = getIntent();
        recipientId = intent.getStringExtra("RECIPIENT_ID");
        currentUserId = ParseUser.getCurrentUser().getObjectId();
        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("User");
        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(MessagingActivity1.this, "Message failed to send.",
                    Toast.LENGTH_LONG).show();
        }

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

        @Override
        public void onMessageSent(MessageClient client, Message message,
                String recipientId) {
            final WritableMessage writableMessage = new WritableMessage(message
                    .getRecipientIds().get(0), message.getTextBody());
            // only add message to parse database if it doesn't already exist
            // there
            ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
            query.whereEqualTo("doobaId", 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(
                                    "User");
                            parseMessage.put("senderId", currentUserId);
                            parseMessage.put("recipientId", writableMessage
                                    .getRecipientIds().get(0));
                            parseMessage.put("messageText",
                                    writableMessage.getTextBody());
                            parseMessage.put("doobaId",
                                    writableMessage.getMessageId());
                            parseMessage.saveInBackground();
                            messageAdapter.addMessage(writableMessage,
                                    MessageAdapter.DIRECTION_OUTGOING);
                        }
                    }
                }
            });
        }

        @Override
        public void onMessageDelivered(MessageClient client,
                MessageDeliveryInfo deliveryInfo) {
        }

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

以下是留言服务活动:

public class MessageService extends Service implements SinchClientListener {

    private static final String APP_KEY = "code;
    private static final String APP_SECRET = "code";
    private static final String ENVIRONMENT = "code";
    private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
    private SinchClient sinchClient = null;
    private MessageClient messageClient = null;
    private String currentUserId;
    private LocalBroadcastManager broadcaster;
    private Intent broadcastIntent = new Intent(
            "com.dooba.beta.MatchOptionActivity1");

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        currentUserId = ParseUser.getCurrentUser().getObjectId();
        if (currentUserId != null && !isSinchClientStarted()) {
            startSinchClient(currentUserId);
        }
        broadcaster = LocalBroadcastManager.getInstance(this);
        return super.onStartCommand(intent, flags, startId);
    }

    public void startSinchClient(String username) {
        sinchClient = Sinch.getSinchClientBuilder().context(this)
                .userId(username).applicationKey(APP_KEY)
                .applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT)
                .build();
        sinchClient.addSinchClientListener(this);
        sinchClient.setSupportMessaging(true);
        sinchClient.setSupportActiveConnectionInBackground(true);
        sinchClient.checkManifest();
        sinchClient.start();
    }

    private boolean isSinchClientStarted() {
        return sinchClient != null && sinchClient.isStarted();
    }

    @Override
    public void onClientFailed(SinchClient client, SinchError error) {
        broadcastIntent.putExtra("success", false);
        broadcaster.sendBroadcast(broadcastIntent);
        sinchClient = null;
    }

    @Override
    public void onClientStarted(SinchClient client) {
        broadcastIntent.putExtra("success", true);
        broadcaster.sendBroadcast(broadcastIntent);
        client.startListeningOnActiveConnection();
        messageClient = client.getMessageClient();
    }

    @Override
    public void onClientStopped(SinchClient client) {
        sinchClient = null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return serviceInterface;
    }

    @Override
    public void onLogMessage(int level, String area, String message) {
    }

    @Override
    public void onRegistrationCredentialsRequired(SinchClient client,
            ClientRegistration clientRegistration) {
    }

    public void sendMessage(String recipientUserId, String textBody) {
        if (messageClient != null) {
            WritableMessage message = new WritableMessage(recipientUserId,
                    textBody);
            messageClient.send(message);
        }
    }

    public void addMessageClientListener(MessageClientListener listener) {
        if (messageClient != null) {
            messageClient.addMessageClientListener(listener);
        }
    }

    public void removeMessageClientListener(MessageClientListener listener) {
        if (messageClient != null) {
            messageClient.removeMessageClientListener(listener);
        }
    }

    @Override
    public void onDestroy() {
        sinchClient.stopListeningOnActiveConnection();
        sinchClient.terminate();
    }

    public class MessageServiceInterface extends Binder {
        public void sendMessage(String recipientUserId, String textBody) {
            MessageService.this.sendMessage(recipientUserId, textBody);
        }

        public void addMessageClientListener(MessageClientListener listener) {
            MessageService.this.addMessageClientListener(listener);
        }

        public void removeMessageClientListener(MessageClientListener listener) {
            MessageService.this.removeMessageClientListener(listener);
        }

        public boolean isSinchClientStarted() {
            return MessageService.this.isSinchClientStarted();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

变量

private ServiceConnection serviceConnection = new MyServiceConnection();
private MessageClientListener messageClientListener = new MyMessageClientListener();

可能需要Parse早于onCreate进行初始化,您当前呼叫Parse.initialize;

试试moving the Parse.initialize to Application class