使用 Sinch 发送消息总是失败

Message keeps failing to send with Sinch

我一直在 https://www.sinch.com/tutorials/android-messaging-tutorial-using-sinch-and-parse/#message 学习本教程,但在向其他用户发送消息时遇到问题。当我写一条消息并发送它时。我不断收到一条提示信息 "Message Failed To Send".

这是我的消息服务Activity:

public class MessageService extends Service implements SinchClientListener {

    private static final String APP_KEY = "xxxx";
    private static final String APP_SECRET = "yyyy";
    private static final String ENVIRONMENT = "sandbox.sinch.com";
    private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
    private SinchClient sinchClient = null;
    private MessageClient messageClient = null;
    private String currentUserId;
    private Intent broadcastIntent = new Intent("com.jordanpeterson.textly.messages.ListUsersActivity");
    private LocalBroadcastManager broadCaster;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // get the current user id from parse
        currentUserId = ParseUser.getCurrentUser().getObjectId();
        if (currentUserId != null && !isSinchClientStarted()) {
            startSinchClient(currentUserId);
        }

        broadCaster = LocalBroadcastManager.getInstance(this);

        return super.onStartCommand(intent, flags, startId);
    }

    private void startSinchClient(String userame) {
        sinchClient = Sinch.getSinchClientBuilder().context(this)
                .userId(userame).applicationKey(APP_KEY)
                .applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT)
                .build();
        // this client listener requires that you define
        // a few methods below

        sinchClient.addSinchClientListener(this);

        // Messaging is "turned-on", but calling is not
        sinchClient.setSupportMessaging(true);
        sinchClient.setSupportActiveConnectionInBackground(true);

        sinchClient.checkManifest();
        sinchClient.start();

    }

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

    // The next 5 methods are for the sinch client listener

    @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 void onRegistrationCredentialsRequired(SinchClient client,
            ClientRegistration clientRegistration) {
        // No code in here yet

    }

    @Override
    public void onLogMessage(int level, String area, String message) {
        // No code in here yet either

    }

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

    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 interface for ListUsersActivity & MessagingActivity
    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();
        }
    }

}

这是我的消息Activity:

private String mRecipientId;
    private EditText mMessageBodyField;
    private String mMessageBody;
    private MessageService.MessageServiceInterface messageService;
    private String mCurrentUserId;
    private ServiceConnection serviceConnection = new MyServiceConnection();
    private MessageClientListener messageClientListener = new MyMessageClientListener();

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

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

        // Get RecipientId from the intent
        Intent intent = getIntent();
        mRecipientId = intent.getStringExtra("RECIPIENT_ID");
        mCurrentUserId = ParseUser.getCurrentUser().getObjectId();

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

        // Listen for a click on the send button
        findViewById(R.id.sendButton).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        // Send The Message!
                        mMessageBody = mMessageBodyField.getText().toString();
                        if (mMessageBody.isEmpty()) {
                            Toast.makeText(MessagingActivity.this,
                                    "Please enter a message", Toast.LENGTH_LONG)
                                    .show();
                            return;
                        }
                        messageService.sendMessage(mRecipientId, mMessageBody);
                        mMessageBodyField.setText("");

                    }
                });
    }

    // Unbind the service when the activity is destroyed
    @Override
    protected 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) {
            // Display an incoming message

        }

        @Override
        public void onMessageSent(MessageClient client, Message message,
                String recipientId) {
            // Display the message that was just sent

            // Later, I'll show you how to store the
            // Message in Parse, so you can retrieve and
            // display them every time the conversation is opened

        }

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

        }

        // Don't worry about this right now
        @Override
        public void onShouldSendPushData(MessageClient client, Message message,
                List<PushPair> pushPairs) {

        }

    }

}

这是我的 ListUsersActivity:

public class ListUsersActivity extends Activity {

    private String mCurrentUserId;
    private ArrayAdapter<String> mNamesArrayAdapter;
    private ArrayList<String> mNames;
    private ListView mUsersListView;
    private Button mLogoutButton;
    private ProgressDialog mProgressDialog;
    private BroadcastReceiver mReceiver = null;

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

        mCurrentUserId = ParseUser.getCurrentUser().getObjectId();
        mNames = new ArrayList<String>();

        ParseQuery<ParseUser> query = ParseUser.getQuery();
        // Don't include yourself!
        query.whereNotEqualTo("objectId", mCurrentUserId);
        query.findInBackground(new FindCallback<ParseUser>() {

            @Override
            public void done(List<ParseUser> userList, ParseException e) {
                if (e == null) {
                    for (int i = 0; i < userList.size(); i++) {
                        mNames.add(userList.get(i).getUsername().toString());
                    }
                    mUsersListView = (ListView) findViewById(R.id.usersListView);
                    mNamesArrayAdapter = new ArrayAdapter<String>(
                            getApplicationContext(), R.layout.user_list_item,
                            mNames);
                    mUsersListView.setAdapter(mNamesArrayAdapter);
                    mUsersListView
                            .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                @Override
                                public void onItemClick(AdapterView<?> a,
                                        View v, int i, long l) {
                                    openConversation(mNames, i);

                                }

                                private void openConversation(
                                        ArrayList<String> mNames, int pos) {
                                    ParseQuery<ParseUser> query = ParseUser
                                            .getQuery();
                                    query.whereEqualTo("username",
                                            mNames.get(pos));
                                    query.findInBackground(new FindCallback<ParseUser>() {

                                        @Override
                                        public void done(List<ParseUser> user,
                                                ParseException e) {
                                            if (e == null) {
                                                Intent intent = new Intent(ListUsersActivity.this, MessagingActivity.class);
                                                intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
                                                startActivity(intent);
                                            } else {
                                                Toast.makeText(
                                                        getApplicationContext(),
                                                        "Error finding that user!",
                                                        Toast.LENGTH_LONG)
                                                        .show();
                                            }

                                        }
                                    });

                                }
                            });

                } else {
                    Toast.makeText(ListUsersActivity.this,
                            "Error loading user list", Toast.LENGTH_LONG)
                            .show();
                }

            }
        });



        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("Loading");
        mProgressDialog.setMessage("Please Wait...");
        mProgressDialog.show();

        // broadcast receiver to listen for the broadcast
        // from MessageService

        mReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Boolean success = intent.getBooleanExtra("success", false);
                Toast.makeText(ListUsersActivity.this, "Sinch has started and is working!", Toast.LENGTH_LONG).show();
                mProgressDialog.dismiss();

                // Show a toast message is the Sinch service failed to start
                if (!success) {
                    Toast.makeText(ListUsersActivity.this,
                            "Messaging service failed to start",
                            Toast.LENGTH_LONG).show();
                }

            }

        };

        LocalBroadcastManager
                .getInstance(this)
                .registerReceiver(
                        mReceiver,
                        new IntentFilter(
                                "com.jordanpeterson.textly.messages.ListUsersActivity"));

    }

}

尝试打印消息错误,因为您可能有多种原因。 在 onMessage Failed 函数下,添加此以查看失败消息:

Toast.makeText(MessagingActivity.this,failureInfo.getSinchError().getMessage(), Toast.LENGTH_LONG).show();