I have an iOS app using Sinch which works without a problem, and recently I migrated the app on Android using the very same Sinch credentials(API key and API secret) then I found
12-14 21:57:17.678 17907-17907/com.packagename.android D/SinchClient﹕ onStarted()
12-14 21:57:17.678 17907-17907/com.packagename.android D/SinchClient﹕ mUserAgent.startBroadcastListener()
12-14 21:57:17.678 17907-17907/com.packagename.android D/SinchService﹕ SinchClient started
12-14 21:57:17.738 17907-17907/com.packagename.android I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#4247f4c8 time:23957901
12-14 21:57:21.458 17907-17913/com.packagename.android I/dalvikvm﹕ Total arena pages for JIT: 11
12-14 21:57:21.458 17907-17913/com.packagename.android I/dalvikvm﹕ Total arena pages for JIT: 12
12-14 21:57:21.458 17907-17913/com.packagename.android I/dalvikvm﹕ Total arena pages for JIT: 13
12-14 21:57:21.458 17907-17913/com.packagename.android I/dalvikvm﹕ Total arena pages for JIT: 14
12-14 21:57:21.608 17907-18645/com.packagename.android E/sinch-android-rtc﹕ WARNING: mxp Ignoring message, reason: 'From local instance'
12-14 21:57:21.608 17907-17907/com.packagename.android W/mxp﹕ Ignoring message, reason: 'From local instance'
As seen above, the Sinch client has been started successfully. But onMessageSent is not called, why?
My questions:
Then why it gave me an error while I was trying to send a message?
What does the error: "Ignoring message, reason: 'From local instance'" mean?
SinchService is running and it is not null, why onMessageSent is not called?
Related Code
SinchService.class
public class SinchService extends Service {
private static final String APP_KEY = "xxx";
private static final String APP_SECRET = "xxx";
private static final String ENVIRONMENT = "clientapi.sinch.com";
private static final String TAG = SinchService.class.getSimpleName();
private final SinchServiceInterface mServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient = null;
private StartFailedListener mListener;
public class SinchServiceInterface extends Binder {
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public void sendMessage(String recipientUserId, String textBody) {
SinchService.this.sendMessage(recipientUserId, textBody);
}
public void receiveMessage(String payload) {
SinchService.this.receiveMessage(payload);
}
public void addMessageClientListener(MessageClientListener listener) {
SinchService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
SinchService.this.removeMessageClientListener(listener);
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
if (mSinchClient != null && mSinchClient.isStarted()) {
mSinchClient.terminate();
}
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return mServiceInterface;
}
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
public void sendMessage(String recipientUserId, String textBody) {
if (isStarted()) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
mSinchClient.getMessageClient().send(message);
}
}
public void receiveMessage(String payload) {
if (isStarted()) {
NotificationResult result = mSinchClient.relayRemotePushNotificationPayload(payload);
if (result.isMessage()) {
String msgId = result.getMessageResult().getMessageId();
Log.i(TAG, String.format("Received msg Id %s", msgId));
}
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (mSinchClient != null) {
mSinchClient.getMessageClient().addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (mSinchClient != null) {
mSinchClient.getMessageClient().removeMessageClientListener(listener);
}
}
private void start(String userName) {
if (mSinchClient == null) {
mSinchClient = Sinch.getSinchClientBuilder()
.context(getApplicationContext())
.userId(userName)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT).build();
mSinchClient.setSupportMessaging(true);
mSinchClient.setSupportPushNotifications(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.checkManifest();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.start();
}
}
private void stop() {
if (mSinchClient != null) {
mSinchClient.stopListeningOnActiveConnection();
mSinchClient.terminate();
mSinchClient = null;
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
}
SinchManager.class
public class SinchManager implements MessageClientListener, ServiceConnection {
private SinchCallback callback;
private static final String TAG = SinchManager.class.getSimpleName();
private Context context;
private SinchService.SinchServiceInterface mSinchServiceInterface;
private String chatRecipient;
public SinchManager(Context c, SinchCallback cb) {
this.context = c;
this.callback = cb;
// init Sinch
context.getApplicationContext().bindService(new Intent(context, SinchService.class), this,
context.BIND_AUTO_CREATE);
}
public void sendMessage(String recipient, String msg) {
mSinchServiceInterface.sendMessage(recipient, msg);
}
public void stopSinchClient() {
mSinchServiceInterface.removeMessageClientListener(this);
mSinchServiceInterface.stopClient();
context.stopService(new Intent(context, SinchService.class));
context.unbindService(this);
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
mSinchServiceInterface.addMessageClientListener(this);
if (!mSinchServiceInterface.isStarted()) {
mSinchServiceInterface.startClient(username);/// Here username="xxx"
}
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = null;
}
}
#Override
public void onIncomingMessage(MessageClient messageClient, Message message) {
callback.onReceiveSinchMessage(message);
}
#Override
public void onMessageSent(MessageClient messageClient, Message message, String s) {
callback.onSentSinchMessage(message, s);
}
#Override
public void onMessageFailed(MessageClient messageClient, Message message, MessageFailureInfo failureInfo) {
callback.onFailedSinchMessage(failureInfo);
}
#Override
public void onMessageDelivered(MessageClient messageClient, MessageDeliveryInfo deliveryInfo) {
callback.onDeliveredSinchMessage(deliveryInfo);
}
#Override
public void onShouldSendPushData(MessageClient messageClient, Message message, List<PushPair> pushPairs) {
//TODO setup offline push notification
Log.d(TAG, "Recipient not online. And it's not in public chat \n Should notify recipient using push");
}
}
On my activity class, I send the message like this:
private void sendMessage() {
String textBody = messageTextBox.getText().toString();
if (chatRecipient.isEmpty()) {
Log.e(TAG, "Recipient is empty, Check Activity Bundle");
return;
}
if (textBody.isEmpty()) {
Toast.makeText(this, "No text message", Toast.LENGTH_SHORT).show();
return;
}
sinchManager.sendMessage(chatRecipient, textBody);
messageTextBox.setText("");
}
Sinch Sample Code
I just tried the sample code Sinch provided and it also shows me the same error code:
12-16 22:48:37.713 7648-8096/com.sinch.android.rtc.sample.messaging E/sinch-android-rtc﹕ WARNING: mxp Ignoring message, reason: 'From local instance'
12-16 22:48:37.713 7648-7648/com.sinch.android.rtc.sample.messaging W/mxp﹕ Ignoring message, reason: 'From local instance'
12-16 22:48:37.863 7648-7648/com.sinch.android.rtc.sample.messaging D/MessageClient﹕ onSentMessage: NativeMessage [id=xxxxx, nativeAddress=xxxx] to recipient with idxxx
However I noticed that the last line of log indicates that the Message was successfully sent.
I am confused right now, is there anyone who has experience on this?
NOTE: the sample code use the same API KEY/SECRET/Environment as the one I showed above.
Download Sinch Sample Code
Related
I am trying to integrate the Sinch API in android .
My VOIPClient. Java is like this
public class VOIPClient {
private static final String TAG = "VOIPClient";
private SinchClient mSinch;
private TTSHelper mTTS;
private Call mCurrentCall;
private BootService mContext;
private SinchClientBuilder mBuilder;
private NsdController mNsdController;
private final CallListener mCallListener = new CallListener() {
#Override
public void onCallProgressing(Call call) {
Log.d(TAG, "Call established at " + " Thusee");
}
#Override
public void onCallEstablished(Call call) {
Log.d(TAG, "Call established at " + call.getDetails().getEstablishedTime());
mTTS.speak("Call started", TTSHelper.UTTERANCE_VOIP_START);
JsonObject payload = new JsonObject();
payload.addProperty("Status", 0);
payload.addProperty("Call_status", 1);
if (mNsdController != null) {
mNsdController.sendCommand(20, payload);
}
}
#Override
public void onCallEnded(Call call) {
Log.d(TAG, "Call ended at " + call.getDetails().getEndedTime() + "caused by " + call.getDetails().getEndCause().toString());
mTTS.speak("Call ended", TTSHelper.UTTERANCE_VOIP_END);
mCurrentCall.hangup();
JsonObject payload = new JsonObject();
payload.addProperty("Status", 0);
payload.addProperty("Call_status", 1);
if (mNsdController != null) {
mNsdController.sendCommand(21, payload);
}
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> list) {
}
};
public VOIPClient(BootService context) {
mContext = context;
mTTS = TTSHelper.getInstance(context);
mBuilder = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext())
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT);
if (mNsdController != null)
mNsdController.initialize();
}
public void start() {
SharedPreferences prefs = mContext.getPreferences();
int userId = prefs.getInt(MerryClient.PREF_USER_ID, 0);
String mUserId;
if (userId > 0) {
mUserId = String.valueOf(userId);
mSinch = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext()).userId(mUserId)
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT).build();
mSinch.setSupportCalling(true);
mSinch.setSupportManagedPush(false);
SinchClientListener sinchClientListener = new SinchClientListener() {
#Override
public void onClientStarted(SinchClient sinchClient) {
Log.d(TAG, "Sinch Client starts: " + sinchClient.getLocalUserId());
mTTS.speak("Call ready", TTSHelper.UTTERANCE_VOIP_READY);
}
#Override
public void onClientStopped(SinchClient sinchClient) {
Log.d(TAG, "Sinch Client stops");
}
#Override
public void onClientFailed(SinchClient sinchClient, SinchError sinchError) {
Log.e(TAG, String.format("Sinch Client error %d: %s", sinchError.getCode(), sinchError.getMessage()));
mSinch.terminate();
mTTS.speak("Voice Over IP failed", TTSHelper.UTTERANCE_VOIP_FAIL);
}
#Override
public void onRegistrationCredentialsRequired(SinchClient sinchClient, ClientRegistration clientRegistration) {
Log.d(TAG, "Sinch Client requires registration");
}
#Override
public void onLogMessage(int i, String s, String s1) {
Log.d(TAG, s1);
}
};
mSinch.addSinchClientListener(sinchClientListener);
mSinch.getCallClient().setRespectNativeCalls(false);
mSinch.getCallClient().addCallClientListener(new SinchCallClientListener());
mCurrentCall = null;
mSinch.startListeningOnActiveConnection();
mSinch.start();
}
}
public void tearDown() {
if (mSinch != null) {
mSinch.stopListeningOnActiveConnection();
mSinch.terminate();
mSinch = null;
}
}
public void restart() {
tearDown();
start();
}
public void initiateCall(final String targetUserName) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
if (targetUserName != null) {
try {
Call call = callUser(targetUserName);
call.addCallListener(mCallListener);
mCurrentCall = call;
} catch (Exception e) {
Log.e(TAG, "Initiate VOIP call failed", e);
}
}
Looper.loop();
}
}).start();
}
public void answerCall() {
if (mCurrentCall != null) {
mCurrentCall.answer();
}
}
public void hangUpCall() {
if (mCurrentCall != null) {
mCurrentCall.hangup();
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
mTTS.speak("Incoming call from " + call.getRemoteUserId(), TTSHelper.UTTERANCE_VOIP_INCOMING);
call.addCallListener(mCallListener);
mCurrentCall = call;
// For testing only
answerCall();
}
}
public Call callUser(String userId) {
if (mSinch != null && mSinch.isStarted()) {
start();
}
if (mSinch == null) {
return null;
}
return mSinch.getCallClient().callUser(userId);
}
class CallerThread implements Runnable {
public String mtargetUserName;
CallerThread(String targetUserName) {
this.mtargetUserName = targetUserName;
}
#Override
public void run() {
Looper.prepare();
if (mtargetUserName != null) {
try {
Call call = callUser(mtargetUserName);
call.addCallListener(mCallListener);
mCurrentCall = call;
} catch (Exception e) {
Log.e(TAG, "Initiate VOIP call failed", e);
mContext.getAlexa().start();
}
}
Looper.loop();
}
}
}
When I try to call to other device then I am getting these kind of exceptions
Initiate VOIP call failed
java.lang.IllegalStateException: SinchClient not started
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.throwUnlessStarted(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.call(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(Unknown Source)
at tw.com.test.cloud.VOIPClient.callUser(VOIPClient.java:272)
at tw.com.test.cloud.VOIPClient$CallerThread.run(VOIPClient.java:293)
at java.lang.Thread.run(Thread.java:818)
Also some times I am getting this exception
FATAL EXCEPTION: Thread-75
Process: tw.com.test.wear, PID: 1123
java.lang.IllegalThreadStateException: A Looper must be associated with this thread.
at com.sinch.android.rtc.internal.AndroidLooperCallbackHandler.<init>(Unknown Source)
at com.sinch.android.rtc.internal.client.InternalSinchClientFactory.createSinchClient(Unknown Source)
at com.sinch.android.rtc.DefaultSinchClientBuilder.build(Unknown Source)
at tw.com.test.cloud.VOIPClient.start(VOIPClient.java:109)
at tw.com.test.cloud.VOIPClient$2.onClientStopped(VOIPClient.java:124)
at com.sinch.android.rtc.internal.client.DefaultSinchClient.shutdown(Unknown Source)
at com.sinch.android.rtc.internal.client.DefaultSinchClient.terminate(Unknown Source)
at tw.com.test.cloud.VOIPClient.tearDown(VOIPClient.java:160)
at tw.com.test.nsd.NsdController.messageReceived(NsdController.java:570)
at tw.com.test.nsd.NsdConnection.run(NsdConnection.java:115)
at java.lang.Thread.run(Thread.java:818)
2 Days I tried my self, I can't able to solve this yet,
I am always getting these exception. Sometimes it will work for one time then I need to restart the app.
You have to start SinchClient sinchClient.start(); and take NOTE during production mode do not place in a plain text form your SINCH_APP_SECRET, because its a secret key, hackers will easily read or decompile your code.
public VOIPClient(BootService context) {
mContext = context;
mTTS = TTSHelper.getInstance(context);
mBuilder = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext())
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT);
sinchClient.setSupportCalling(true);
sinchClient.start();
if (mNsdController != null)
mNsdController.initialize();
}
We are using qucikblox sdk 2.0 in online consultation mobile application in both platform ios & android. But recently facing issue that if A user device is locked or A user is not using app and if B user calls A user over audio/video A user will not get call.
Case 1-- Device locked app is in foreground User A will be getting a call from user B but user A will not get to know about a call when user A unlock device then only user A can see call notification.
Case 2-- App is in background & device is unlocked User A will not get a audio.video call, evn push message of chats also not receiving
Create a sticky service which will run in background even activity destroy, this service is responsible for QBsession and all other operations so it will detect call in background so you will create Session in service , not in CallActivity. Iam successfully implements this and iam successfully receiving calls in background by this.
public class BloxService extends Service implements QBRTCClientSessionCallbacks {
private QBChatService chatService;
private volatile boolean resultReceived = true;
static final String APP_ID = "";
static final String AUTH_KEY = "";
static final String AUTH_SECRET = "";
static final String ACCOUNT_KEY = "";
private QBRTCClient rtcClient;
public static BloxService bloxService;
private static final String TAG = "BloxService";
public boolean isSessionRunning;
public boolean isCallRunning;
private Date tokenExpirationDate;
private QBAuth qbAuth;
private AppPrefs prefs;
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
/*boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);*/
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
//NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo!=null && currentNetworkInfo.isConnected()){
if(!QBChatService.getInstance().isLoggedIn()){
if(!isSessionRunning) {
initializeQb();
}
}
}
}
};
#Override
public void onCreate() {
super.onCreate();
// prefs = AppPrefs.getInstance(getApplicationContext()); // for testing we put this line on start
registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("bloxservice","onDestroy");
try{
unregisterReceiver(mConnReceiver);
}catch (Exception e){
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
prefs = AppPrefs.getInstance(getApplicationContext());
if (prefs.getData(IS_USER_LOGIN, false)) {
Log.d("bloxservice","start");
try {
if (!QBChatService.getInstance().isLoggedIn()) {
initializeQb();
}
}catch (Exception e)
{
initializeQb();
}
bloxService=this;
}
else {
stopSelf();
}
return START_STICKY;
}
public static BloxService getBloxService() {
return bloxService;
}
public void initializeQb(){
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
QBChatService.setDebugEnabled(true);
// added on 20 july
QBChatService.setDefaultAutoSendPresenceInterval(60);
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(60); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
// QBChatService.getInstance().startAutoSendPresence(10);// added on 20 july
chatService = QBChatService.getInstance();
/* tokenExpirationDate = qbAuth.getTokenExpirationDate();
try {
String Token= QBAuth.getSession().toString();
QBAuth.createFromExistentToken()
} catch (QBResponseException e) {
e.printStackTrace();
}
*/
if(AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.IS_USER_LOGIN,false)){
Log.e("Login Process", "Started");
isSessionRunning=true;
String userId=AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.USER_ID,"");
String name=AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.USER_NAME,"");
String picUrl=AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.USER_IMAGE,"");
String phone=prefs.getData(Constants.PrefsConstatnt.USER_PHONE, "");
if(name.isEmpty()){
name=userId;
}
createAppSession(Integer.parseInt(userId)<10?"0"+userId:userId,name,userId,picUrl,phone);
}
}
private void createAppSession(final String userId, final String name,final String exId,final String picUrl,final String phone) {
QBAuth.createSession(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
loadUsers(userId, name, exId,picUrl,phone);
final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
}
// Subscribe to Push Notifications
//subscribeToPushNotifications(registrationId);
}
#Override
public void onError(QBResponseException exc) {
exc.printStackTrace();
isSessionRunning=false;
}
});
}
//QBUser users;
public void loadUsers(String userId,String name,String exId,String picUrl,String phone) {
final QBUser userr = new QBUser(userId, DataHolder.PASSWORD);
userr.setFullName(name);
userr.setExternalId(exId);
userr.setCustomData(picUrl);
userr.setPhone(phone);
QBUsers.signUp(userr, new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
createSession(userr.getLogin(), userr.getPassword());
}
#Override
public void onError(QBResponseException error) {
error.printStackTrace();
QBUsers.signIn(userr, new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
createSession(userr.getLogin(), userr.getPassword());
}
#Override
public void onError(QBResponseException error) {
error.printStackTrace();
isSessionRunning = false;
}
});
}
});
}
private void createSession(final String login, final String password) {
final QBUser user = new QBUser(login, password);
QBAuth.createSession(login, password, new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession session, Bundle bundle) {
user.setId(session.getUserId());
Log.e("User" + session.getUserId(), "Login");
QBSettings.getInstance().fastConfigInit(APP_ID, AUTH_KEY, AUTH_SECRET);
sendRegistrationToServer(AppPrefs.getInstance(BloxService.this).getData(Constants.PrefsConstatnt.DEVICE_TOKEN, ""));
DataHolder.setLoggedUser(user);
if (chatService.isLoggedIn()) {
resultReceived = true;
initQBRTCClient();
isSessionRunning = false;
} else {
chatService.login(user, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void result, Bundle bundle) {
initQBRTCClient();
resultReceived = true;
isSessionRunning = false;
}
#Override
public void onError(QBResponseException exc) {
resultReceived = true;
isSessionRunning = false;
}
});
}
/* QBRosterListener rosterListener = new QBRosterListener() {
#Override
public void entriesDeleted(Collection<Integer> userIds) {
Log.d("mayanks","changed");
}
#Override
public void entriesAdded(Collection<Integer> userIds) {
Log.d("mayanks","changed");
}
#Override
public void entriesUpdated(Collection<Integer> userIds) {
Log.d("mayanks","changed");
}
#Override
public void presenceChanged(QBPresence presence) {
Log.d("mayanks","changed");
}
};
QBSubscriptionListener subscriptionListener = new QBSubscriptionListener() {
#Override
public void subscriptionRequested(int userId) {
}
};
QBRoster chatRoster = QBChatService.getInstance().getRoster(QBRoster.SubscriptionMode.mutual, subscriptionListener);
chatRoster.addRosterListener(rosterListener);
Collection<QBRosterEntry> entries = chatRoster.getEntries();
QBPresence presence = chatRoster.getPresence(9);
if (presence!=null) {
if (presence.getType() == QBPresence.Type.online) {
Log.d("mayanks","online");
// User is online
}else{
Log.d("mayanks","offline");
// User is offline
}
}*/
}
#Override
public void onError(QBResponseException exc) {
resultReceived = true;
isSessionRunning = false;
}
});
}
private void sendRegistrationToServer(final String token) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
String deviceID = prefs.getString(PROPERTY_DEVICE_ID, null);
if(deviceID==null)
{
deviceID=DeviceUtils.getDeviceUid();
storeDeviceId(getApplicationContext(),deviceID);
}
QBSubscription qbSubscription = new QBSubscription();
qbSubscription.setNotificationChannel(QBNotificationChannel.GCM);
qbSubscription.setDeviceUdid(deviceID);
qbSubscription.setRegistrationID(token);
qbSubscription.setEnvironment(QBEnvironment.DEVELOPMENT); // Don't forget to change QBEnvironment to PRODUCTION when releasing application
QBPushNotifications.createSubscription(qbSubscription,
new QBEntityCallback<ArrayList<QBSubscription>>() {
#Override
public void onSuccess(ArrayList<QBSubscription> qbSubscriptions, Bundle bundle) {
Log.e(TAG, "Successfully subscribed for QB push messages");
//saveGcmRegIdToPreferences(gcmRegId);
isSessionRunning=false;
}
#Override
public void onError(QBResponseException error) {
Log.e(TAG, "Unable to subscribe for QB push messages; " + error.toString());
isSessionRunning=false;
}
});
}
});
}
#Override
public void onReceiveNewSession(final QBRTCSession qbrtcSession) {
Log.d("bloxservice","CallRecive");
new Handler().post(new Runnable() {
#Override
public void run() {
if(!isCallRunning) {
DataHolder.incomingSession = qbrtcSession;
/* Map<String,String> userInfo = qbrtcSession.getUserInfo();
String s=userInfo.get("mayank");*/
Intent intent = new Intent(BloxService.this, CallActivity.class);
intent.putExtra("incoming", true);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else{
Log.e("User","Busy");
}
}
});
}
#Override
public void onUserNotAnswer(QBRTCSession qbrtcSession, Integer integer) {
// ToastUtil.showShortToast(this, "no answer");
}
#Override
public void onCallRejectByUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
// ToastUtil.showShortToast(this,"rejected");
}
#Override
public void onCallAcceptByUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
//ToastUtil.showShortToast(this,"accepted");
}
#Override
public void onReceiveHangUpFromUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
}
#Override
public void onUserNoActions(QBRTCSession qbrtcSession, Integer integer) {
// ToastUtil.showShortToast(this,"no Action");
}
#Override
public void onSessionClosed(QBRTCSession qbrtcSession) {
// ToastUtil.showShortToast(this,"onSessionClosed");
}
#Override
public void onSessionStartClose(QBRTCSession qbrtcSession) {
// ToastUtil.showShortToast(this,"onSessionStartClose");
}
private void initQBRTCClient() {
rtcClient = QBRTCClient.getInstance(this);
QBVideoChatWebRTCSignalingManager qbChatService = QBChatService.getInstance().getVideoChatWebRTCSignalingManager();
if (qbChatService != null) {
qbChatService.addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
#Override
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally) {
if (!createdLocally) {
rtcClient.addSignaling((QBWebRTCSignaling) qbSignaling);
}
}
});
QBRTCConfig.setMaxOpponentsCount(2);
QBRTCConfig.setDisconnectTime(40);
QBRTCConfig.setAnswerTimeInterval(30l);
QBRTCConfig.setDebugEnabled(true);
rtcClient.addSessionCallbacksListener(this);
rtcClient.prepareToProcessCalls();
QBChatService.getInstance().addConnectionListener(new AbstractConnectionListener() {
#Override
public void connectionClosedOnError(Exception e) {
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
});
}
}
public void logout(){
chatService.logout(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void result, Bundle bundle) {
}
#Override
public void onError(QBResponseException list) {
}
});
}
/* public void subscribeToPushNotifications(String registrationID) {
QBSubscription subscription = new QBSubscription(QBNotificationChannel.GCM);
subscription.setEnvironment(QBEnvironment.DEVELOPMENT);
//
String deviceId;
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(
Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null) {
deviceId = mTelephony.getDeviceId(); /*//*** use for mobiles
} else {
deviceId = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID); /*//*** use for tablets
}
subscription.setDeviceUdid(deviceId);
//
subscription.setRegistrationID(registrationID);
//
QBPushNotifications.createSubscription(subscription, new QBEntityCallback<ArrayList<QBSubscription>>() {
#Override
public void onSuccess(ArrayList<QBSubscription> subscriptions, Bundle args) {
Log.d("push_send","sucess");
}
#Override
public void onError(QBResponseException error) {
Log.d("push_send","sucess");
}
});
}*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences,
// but
// how you store the regID in your app is up to you.
Log.e("getGCMPreferences", "package= " + context.getPackageName());
return getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
}
private void storeDeviceId(Context context, String deviceId) {
final SharedPreferences prefs = getGCMPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_DEVICE_ID, deviceId);
editor.commit();
}
}
I'm trying to understand a piece of code that uses Android Binders and Messages to perform IPC. I've read a few articles, papers and slides on binders, but I'm still confused and have a hard time understanding the code, since I didn't encounter any tutorials/examples of actually implementing binders in java code. I am listing down the sanitized/abbreviated code below as well as my understanding of what it does and where it gets confusing. I would appreciate if someone could help me understand this, especially pertaining to the flow of Parcels and Messages.
MyService.java
public class MyService extends Service
{
private final IMyService.Stub mBinder;
private Context _mContext;
private MyServiceHandler mHandler;
private HanderThread mHandlerThread;
private IHelperService mHelperService;
public MyService() {
this.mBinder = new IMyService.Stub() {
public void start_data(final String data) {
try {
if (MyService.this.mHelperService == null) {
return;
}
Message msg = MyService.this.getHandler().obtainMessage(3, (Object)data);
MyService.this.getHandler().sendMessage(msg);
} catch (SecurityException ex) {
// do some logging
}
};
}
private void startMessageProcess(final String message) {
// Process the message argument
final byte[] dataArray = this.getByteArray(message);
byte[] returnData;
try {
returnData = this.mHelperService.foo(dataArray);
} catch (Exception e) {
// do some logging
}
Message msg = this.getHandler().obtainMessage(3, (Object)message);
this.getHandler.sendMessage(msg);
}
private String getServerData(int id) {
// builds a Uri based on id and posts it, retrieves String data from HTTP entity and returns it
}
private boolean postDataToServer(final byte[] arrayData) {
// builds a Uri, post data to it, gets the status code, returns true if successful
}
private void sendData(final byte[] arrayData) {
final Intent intent = new Intent();
intent.setAction("com.my.service.intent.action.MY_RESULT");
intent.putExtra("com.my.service.intent.extra.RESULT", 0);
intent.putExtra("com.my.service.intent.extra.MY_DATA", arrayData);
this._mContext.sendBroadcast(intent, "com.my.service.permission.MY_PERMISSION");
}
public Handler getHandler() {
return this.mHandler;
}
public IBinder onBind(final Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (action != null && action.equals("com.my.service.intent.action.BIND_MY_SERVICE")) {
this._mContext = this.getApplicationContext();
return (IBinder)this.mBinder;
}
}
return null;
}
public void onCreate() {
super.onCreate();
try {
final Class<?> serviceManager = Class.forName("android.os.ServiceManager");
this.mHelperService = mHelperService.Stub.asInterface((IBinder)serviceManager.getMethod("getService", String.class).invoke(serviceManager, "helperservice"));
if (this.mHelperService == null) {
return;
}
}
catch (ClassNotFoundException ex2) {
Log.e("MyService", "Helper service ClassNotFoundException !!!");
}
catch (Exception ex) {
Log.e("MyService", "onCreate() Exception: " + Log.getStackTraceString((Throwable)ex));
}
this.mHandlerThread = new HandlerThread("MyService");
this.mHandlerThread.start();
this.mHandler = new MyServiceHandler(this.mHandlerThread.getLooper());
}
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if (intent != null) {
super.onStartCommand(intent, flags, startId);
}
return START_NOT_STICKY;
}
private final class MyService Handler extends Handler
{
public MyServiceHandler(final Looper looper) {
super(looper);
}
public void handleMessage(final Message message) {
if (message != null) {
switch (message.what) {
case 2: {
final String data = (String)message.obj;
if (data != null) {
MyService.this.startMessageProcess(data);
return
}
break;
}
case 3: {
MyService.this.sendData((byte[])message.obj);
}
}
}
}
}
}
IMyService.java
public interface IMyService extends IInterface
{
void start_data(final String p0) throws RemoteException;
public abstract static class Stub extends Binder implements IMyService
{
public Stub() {
this.attachInterface((IInterface)this, "com.my.service.IMyService");
}
public static IMyService asInterface(final IBinder binder) {
if (binder == null) {
return null;
}
final IInterface queryLocalInterface = binder.queryLocalInterface("com.my.service.IMyService");
if (queryLocalInterface != null && queryLocalInterface instanceof IMyService) {
return (IMyService)queryLocalInterface;
}
return new Proxy(binder);
}
public IBinder asBinder() {
return (IBinder)this;
}
public boolean onTransact(final int code, final Parcel data, final Parcel reply, final int flags) throws RemoteException {
switch (code) {
case 1: {
data.enforceInterface("com.my.service.IMyService");
this.start_data(data.readString());
reply.writeNoException();
return true;
}
case 1000000000: {
reply.writeString("com.my.service.IMyService");
return true;
}
default: {
return super.onTransact(n, data, reply, flags);
}
}
}
private static class Proxy implements IMyService
{
private IBinder mRemote;
Proxy(final IBinder mRemote) {
this.mRemote = mRemote;
}
public IBinder asBinder() {
return this.mRemote;
}
public String getInterfaceDescriptor() {
return "com.my.service.IMyService";
}
#Override
public void start_data(final String data) throws RemoteException {
final Parcel data = Parcel.obtain();
final Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken("com.my.service.IMyService");
data.writeString(data);
this.mRemote.transact(1, data, reply, 0);
reply.readException();
}
finally {
reply.recycle();
data.recycle();
}
}
}
}
}
IHelperService.java
public interface IHelperService extends IInterface
{
// a bunch of method declarations here
public abstract static class Stub extends Binder implements IHelperService
{
public Stub() {
this.attachInterface((IInterface)this, "android.service.helper.IHelperService");
}
public static IHelperService asInterface(final IBinder binder) {
if (binder == null) {
if (queryLocalInterface != null && queryLocalInterface instanceof IHelperService) {
return (IHelperService)queryLocalInterface;
}
return new Proxy(binder);
}
}
public IBinder asBinder() {
return (IBinder)this;
}
public boolean onTransact(int code, final Parcel data, final Parcle reply, int flags) throws RemoteException {
switch (code) {
// does a bunch of bunch of stuff here based on the incoming code
}
}
}
private static class Proxy implements IHelperService
{
private IBinder mRemote;
Proxy(final IBinder mRemote) {
this.mRemote = mRemote;
}
#Override
// a bunch of method definitions here, everything that was declared above
}
}
I'm having a hard time tracing who sends what to who. For example, in the Proxy of IMyService, start_data calls transact(mRemote), but who is mRemote? Also, in the MyService() constructor as well as startMessageProcess, there are calls to sendMessage, who is it sending to?
Then, there are private methods in MyService that don't seem to be called locally, such as startMessageProcess and getServerData. Who else can call these methods if they're private?
I see this error when passing the target and onboardee wifinetwork configurations to the onboarding sdk.
This is the piece of code where the error occurs.
ConfigureWifiMode res1 = this.onboardingClient.configureWiFi(this.onboardingConfiguration.getTarget().getSSID(), passForConfigureNetwork, this.onboardingConfiguration.getTarget().getAuthType());
Log.i("OnboardingManager", "configureWiFi result=" + res1);
switch(OnboardingManager.SyntheticClass_1.$SwitchMap$org$alljoyn$onboarding$transport$OnboardingTransport$ConfigureWifiMode[res1.ordinal()]) {
case 1:
this.onboardingClient.connectWiFi();
return new OnboardingManager.DeviceResponse(OnboardingManager.DeviceResponse.ResponseCode.Status_OK);
case 2:
return new OnboardingManager.DeviceResponse(OnboardingManager.DeviceResponse.ResponseCode.Status_OK_CONNECT_SECOND_PHASE);
default:
Log.e("OnboardingManager", "configureWiFi returned an unexpected result: " + res1);
return new OnboardingManager.DeviceResponse(OnboardingManager.DeviceResponse.ResponseCode.Status_ERROR);
}
Here is my Logcat:
04-28 21:16:35.332 2812-2982/net.holisticlabs.august E/OnboardingManager: onboarddDevice
org.alljoyn.bus.BusException: ER_BUS_SECURITY_NOT_ENABLED
Any help will be great! Thanks!
Try to add an authentication listener to the bus attachment:
/* set keyListener */
String keyStoreFileName = getApplicationContext().getFileStreamPath("alljoyn_keystore").getAbsolutePath();
if (keyStoreFileName != null && keyStoreFileName.length() > 0) {
SrpAnonymousKeyListener authListener = new SrpAnonymousKeyListener(this, m_logger, new String[] { "ALLJOYN_SRP_KEYX", "ALLJOYN_ECDHE_PSK" });
Status authStatus = m_Bus.registerAuthListener(authListener.getAuthMechanismsAsString(), authListener, keyStoreFileName);
if (authStatus != Status.OK) {
Log.d("TAG","Failed to register Auth listener status = " + authStatus.toString());
}
}
private final GenericLogger m_logger = new GenericLogger() {
#Override
public void debug(String TAG, String msg) {
Logg.d(msg);
}
#Override
public void info(String TAG, String msg) {
Logg.i(msg);
}
#Override
public void warn(String TAG, String msg) {
Logg.w(msg);
}
#Override
public void error(String TAG, String msg) {
Logg.e(msg);
}
#Override
public void fatal(String TAG, String msg) {
Logg.d(msg);
}
};
I've been following this tutorial at https://www.sinch.com/tutorials/android-messaging-tutorial-using-sinch-and-parse/#message and I'm having trouble sending the message to another user. When I write a message and send it. I keep getting a toast message that says "Message Failed To Send".
This is my MessageService 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();
}
}
}
This is my MessagingActivity:
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) {
}
}
}
And this is my 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"));
}
}
Try to print the message error because you may have it for many reasons.
Under onMessageFailed function, add this to see the failure message:
Toast.makeText(MessagingActivity.this,failureInfo.getSinchError().getMessage(), Toast.LENGTH_LONG).show();