In my project i user Firebase Database. With it i read data frmo db the following way:
public void getSoftwareRecords() {
final List<Software> softwareList = new ArrayList<>();
databaseReference = firebaseDatabase.getReference("software");
getSoftwareRecordsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
softwareList.add(snapshot.getValue(Software.class));
}
Log.d(TAG, "Software from server count: " + softwareList.size());
onSoftwareTransactionListener.onSuccessSyncListOfSoftware(softwareList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Cant read software list from database: " + databaseError.getDetails());
// TODO describe error #102 for documentation
onSoftwareTransactionListener.onFailureSyncListOfSoftware("Ohh.");
}
};
databaseReference.addValueEventListener(getSoftwareRecordsListener);
After, this method i want to call in IntentService. As u notice, there is no return value = void. So, the question is how i can user service and interface together?
Service (as i wanted to use it):
public class ReadSoftwareListService extends IntentService implements Database.OnSoftwareTransactionListener {
private static final String TAG = ReadSoftwareListService.class.getSimpleName();
public static final String ACTION = "...";
public static final String RESULT_CODE = "RESULT_CODE";
public static final String RESULT_VALUE = "RESULT_VALUE";
private Intent in;
public ReadSoftwareListService() {
super("ReadSoftwareListService");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
in = new Intent(ACTION);
Log.d(TAG, "ReadSoftwareListService:: onHandleIntent");
Database database = new Database(com.google.firebase.database.FirebaseDatabase.getInstance());
database.getSoftwareRecords(); // <- this is a method from code above.
}
#Override
public void onSuccessSyncListOfSoftware(List<Software> softwareList) {
Log.d(TAG, "ReadSoftwareListService:: onSuccessSyncListOfSoftware");
Bundle bundle = new Bundle();
bundle.putInt(RESULT_CODE, Activity.RESULT_OK);
in.putExtras(bundle);
// bundle.putSerializable(RESULT_VALUE, softwareList);
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
#Override
public void onFailureSyncListOfSoftware(String message) {
Log.d(TAG, "ReadSoftwareListService:: onFailureSyncListOfSoftware");
Bundle bundle = new Bundle();
bundle.putInt(RESULT_CODE, Activity.RESULT_CANCELED);
bundle.putString(RESULT_VALUE, message);
in.putExtras(bundle);
LocalBroadcastManager.getInstance(this).sendBroadcast(in);
}
And reciever:
public final BroadcastReceiver softwareListReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "softwareListReceiver:: onReceive");
Bundle bundle = intent.getExtras();
int resultCode = bundle.getInt(RESULT_CODE);
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG, "RESULT CODE == OK");
// softwareListAdapter.updateData(bundle.getParcelableArrayList(RESULT_VALUE));
} else {
Log.d(TAG, "RESULT CODE == CANCEL: " + bundle.getString(RESULT_VALUE));
}
}
};
If you really wanted to use IntentService here, you can go add ResultReceiver as a callback. Example:-
Intent intentService = new Intent(context, YourIntentService.class);
intentService.putExtra(StockService.REQUEST_RECEIVER_EXTRA, new ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == StockService.RESULT_ID_QUOTE) {
...
}
}
});
startService(intentService);
Alternatively you can use Custom AsyncTask by passing interface as one of parameters.
Hope this helps.
Note: Vote up if you like this.
Related
I am starter at Android and now I want to transfer data using intent from one activity to another.
First activity will collect datas and give it to second. but on second the data returns null. So have some errors on there. Here are my code.
public void previewStack(final Context context, final CreateStackNewActivity createStackNewActivity, final Stack stackDetails) {
Map<String, String> options = new HashMap<String, String>();
if(stackDetails.getStackId() != -1){
options.put("stack_id", String.valueOf(stackDetails.getStackId()));
}
int index = 1;
for(StackLineNew stackLine : stackDetails.getLines()){
options.put("title" + index, stackLine.getTitle());
options.put("line_type" + index, Integer.toString(stackLine.getLineType().intValue));
options.put("title" + index, stackLine.getTitle());
if (stackLine.getBody().indexOf("file:/") == -1 && stackLine.getBody().indexOf("content:") == -1) {
options.put("description" + index, stackLine.getBody());
if (stackLine.getLineId() != -1) {
options.put("line_id" + index, Integer.toString(stackLine.getLineId()));
}
}
index++;
}
Call<GenericAPIResponse> call = Hype4DAPI.previewStack(stackDetails.getName(), stackDetails.getCategory(), Integer.toString(stackDetails.getLines().size()), options, "");
call.enqueue(new Callback<GenericAPIResponse>() {
#Override
public void onResponse(Call<GenericAPIResponse> call, Response<GenericAPIResponse> response) {
if(response.isSuccessful()) {
GenericAPIResponse saveStackResponse = response.body();
System.out.println(saveStackResponse);
Toast.makeText(context, saveStackResponse.toString(), Toast.LENGTH_SHORT).show();
createStackNewActivity.saveInProgress = false;
createStackNewActivity.somethingHasChanged = false;
createStackNewActivity.updatePostButtonState();
Intent itnt = new Intent(createStackNewActivity, StackDetailsPage.class);
itnt.putExtra("stackId", stackDetails.getStackId());
itnt.putExtra("isPreview", "true");
itnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
createStackNewActivity.startActivity(itnt);
} else {
System.out.println(response.errorBody());
Toast.makeText(context, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GenericAPIResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
And the code of second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stack_details);
final Intent intent = getIntent();
final String stackId;
if (intent != null) { //Null Checking
stackId = intent.getStringExtra("stackId");
isPreview = intent.getStringExtra("isPreview");
stackTitleStr = intent.getStringExtra("stackTitle");
saveLine = (HashMap<String, Object>)intent.getSerializableExtra("saveLine");
}
else{
stackId = null;
}
On second activity, I have all variables are null. isPreview, stackTitleStr, saveLine are all null.
So anyone please help me quickly.
first you should not create the intent in the onResponse callBack method but create a static method in your StackDetailsPage activity that return the intent it needs. With that, this activity "said" to the other ones whats it needs, and it avoid duplicate string extra keys. use this :
//in StackDetailsPage activity
public static Intent getIntent(Context context, String stackId, String...)
{
Intent intent = new Intent(context, StackDetailsPage.class);
intent.putExtra("stackId", stackId);
...
return intent;
}
and then in onResponse method do that :
startActivity(StackDetailsPage.getIntent(context,stackDetails.getStackId(), ...))
Hello I have implemented pusher for realtime chat and subscribing to pusher channel , but I have many activities and fragments where i want to listen to pushr events . I have added this code in every activity/fragment but the problem is that it creates multiple subscriptions for every id . I know that i have to use Singleton for this can anyone point me in the right direction to achieve this ?
Here is the code i am writing in every activity/fragment
private PusherOptions options;
private Channel channel;
private Pusher pusher;
options = new PusherOptions();
options.setCluster("ap2");
pusher = new Pusher("afbfc1f591fd7b70190f", options);
pusher.connect();
profile_id = Global.shared().preferences.getString("PROFILE_ID", " ");
channel = pusher.subscribe(profile_id);
channel.bind("message",
new SubscriptionEventListener() {
#Override
public void onEvent(String s, String s1, final String data) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject result = new JSONObject(data);
String message = result.getString("message");
String time = result.getString("time");
String reId = result.getString("recieverId");
new_message = message;
getConvoData(k, message);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("DATA ====>>" + data);
}
});
}
});
okay so after trying for a while i figured it out my self i created a global class and just added pusher code to it so that it maintains just one connection for the entire lifecycle of the app
public class Global extends MultiDexApplication {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences preferences = sharedInstance.getSharedPreferences(sharedInstance.getString(R.string.shared_preferences), Context.MODE_PRIVATE);
sharedInstance.preferences = preferences;
connectTopusher();
}
public void connectTopusher() {
PusherOptions options;
Channel channel;
Pusher pusher;
options = new PusherOptions();
options.setCluster("ap2");
pusher = new Pusher("afbfc1f591fd7b70190f", options);
pusher.connect();
String profile = Global.shared().preferences.getString("PROFILE_ID", "");
channel = pusher.subscribe(profile);
channel.bind("message",
new SubscriptionEventListener() {
#Override
public void onEvent(String s, String s1, final String data) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
try {
JSONObject result = new JSONObject(data);
String message = result.getString("message");
String time = result.getString("time");
String reId = result.getString("recieverId");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("DATA ====>>" + data);
}
});
}
});
channel.bind("status_change", new SubscriptionEventListener() {
#Override
public void onEvent(String s, String s1, final String data) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
try {
JSONObject result = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("DATA ====>>" + data);
}
});
}
});
}
You can expose channel in your Global class. That will allow you to call bind and unbind in your fragments, when they are in the foreground.
connectToPusher should just create a channel and subscribe to it.
In Global.java:
private Channel channel;
public void connectTopusher() {
PusherOptions options;
Pusher pusher;
options = new PusherOptions();
options.setCluster("ap2");
pusher = new Pusher("afbfc1f591fd7b70190f", options);
pusher.connect();
String profile = Global.shared().preferences.getString("PROFILE_ID", "");
this.channel = pusher.subscribe(profile);
}
public Channel getChannel(){
return this.channel;
}
And then in your activity/fragment you can bind/unbind your listeners to when they are resumed/paused - just keep a reference to it like this:
YourActivity.java (could also be your Fragment)
private SubscriptionEventListener messageListener = new SubscriptionEventListener(){
#Override
public void onEvent(String channel, String event, String data) {
//TODO: do something with events
}
}
//Bind when the listener comes into the foreground:
#Override
protected void onResume() {
super.onResume();
((Global) getActivity().getApplication()).getChannel().bind("message", messageListener);
}
//Make sure to unbind the event listener!
#Override
protected void onPause() {
super.onPause();
((Global) getActivity().getApplication()).getChannel().unbind("message", messageListener);
}
I hope this helps :)
I am building Android App which shows Withings user's activity data in my Application.
But when I am trying to call refresh_token url:
https://oauth.withings.com/account/request_token?oauth_callback=******&oauth_consumer_key=******&oauth_nonce=******&oauth_signature=CcMrI7JaI8M5tEenye3s95wx%2BZ4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1477386344&oauth_version=1.0
Then I am getting Invalid Signature response like below:
{
"status":0,
"message":"Invalid signature :\n CcMrI7JaI8M5tEenye3s95wx+Z4= .. \n{\"oauth_callback\":\"******\",\"oauth_consumer_key\":\"ce54bd6c671546ef8f8d394c0db4bd86688289d5f7fb39f371c5ebce4d01\",\"oauth_nonce\":\"f339febe0fdf4b53b953501e45a049db\",\"oauth_signature\":\"CcMrI7JaI8M5tEenye3s95wx+Z4=\",\"oauth_signature_method\":\"HMAC-SHA1\",\"oauth_timestamp\":\"1477386344\",\"oauth_version\":\"1.0\"}\n{\"base_string\":\"GET&https%3A%2F%2Foauth.withings.com%2Faccount%2Frequest_token&oauth_callback%3D******%26oauth_consumer_key%3D******%26oauth_nonce%3Df339febe0fdf4b53b953501e45a049db%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1477386344%26oauth_version%3D1.0\"}\n{\"key\":\"******\",\"secret\":\"******\",\"callback_url\":null}"
}
First of all you can use the scribe lib
On my sample code I have an Authentication Activity that has an WebView that the user uses to verify the app. Then that Authentication Activity sends back to the MainActivity the response.
On my example I am storing locally on a DB the authenticated user to not ask every time the credentials.
Also I am sending the access token to python server that will get all data stored on Withings Cloud to save it to my Server DB and represent them on a Graph Activity. {I have removed that part}
Because of the copy paste maybe something is missing but most of the code is here
public class WithingsApi extends DefaultApi10a {
private static final String AUTHORIZATION_URL ="https://oauth.withings.com/account/authorize?oauth_token=%s";
private static final String apiKey = "API_KEY";
private static final String apiSecret = "API_SECRET";
#Override
public String getRequestTokenEndpoint() {
return "https://oauth.withings.com/account/request_token";
}
#Override
public String getAccessTokenEndpoint() {
return "https://oauth.withings.com/account/access_token";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return String.format(getAUTHORIZATION_URL(), requestToken.getToken());
}
public static String getKey(){
return apiKey;
}
public static String getSecret(){
return apiSecret;
}
public static String getAUTHORIZATION_URL() {
return AUTHORIZATION_URL;
}
}
#SuppressLint("SetJavaScriptEnabled")
public class AuthenticationActivity extends Activity {
final String LOGTAG = "WITHINGS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
final WebView wvAuthorise = (WebView) findViewById(R.id.wvAuthorise);
wvAuthorise.getSettings().setJavaScriptEnabled(true);
wvAuthorise.setWebViewClient(new MyWebViewClient(wvAuthorise));
MainActivity.service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret())
.build();
new Thread(new Runnable() {
public void run() {
MainActivity.requestToken = MainActivity.service.getRequestToken();
final String authURL = MainActivity.service.getAuthorizationUrl(MainActivity.requestToken);
wvAuthorise.post(new Runnable() {
#Override
public void run() {
wvAuthorise.loadUrl(authURL);
}
});
}
}).start();
}
class MyWebViewClient extends WebViewClient{
WebView wvAuthorise;
MyWebViewClient(WebView wv){
wvAuthorise = wv;
}
#Override
public void onPageFinished(WebView view, String url) {
getUSERID(url);
}
}
private void getUSERID(final String url) {
try {
String divStr = "userid=";
int first = url.indexOf(divStr);
if(first!=-1){
final String userid = url.substring(first+divStr.length());
Intent intent = new Intent();
intent.putExtra("USERID",userid);
setResult(RESULT_OK,intent);
finish();
}
else
{
//...
}
} catch (Exception e) {
Log.e(LOGTAG,e.getMessage());
//...
}
}
}
public class MainActivity extends FragmentActivity {
public static OAuthService service;
public static Token requestToken;
String secret, token;
Token accessToken;
String userId = "";
private UsersDataSource datasource;
private TextView nameTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_mainActivity = this;
nameTV = (TextView) findViewById(R.id.nameTitleTextView);
nameTV.setText("--");
getCredentials();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == AUTHENTICATION_REQUEST) {
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
if (extras != null) {
userId = extras.getString("USERID");
getAccessTokenThread.execute((Object) null);
}
}
}
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
private void getCredentials() {
try {
datasource = new UsersDataSource(this);
datasource.open();
List<User> users = datasource.getAllUsers();
if (users.isEmpty()) {
startAuthenticationActivity();
} else {
// TODO load all users and if isn't anyone correct
// startAuthenticationActivity
secret = users.get(0).getSecret();
token = users.get(0).getToken();
userId = users.get(0).getUserId();
Log.i(LOGTAG, "secret : " + secret);
Log.i(LOGTAG, "token : " + token);
Log.i(LOGTAG, "userId : " + userId);
try {
service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret()).build();
accessToken = new Token(token, secret);
loadData();
} catch (Exception ex) {
startAuthenticationActivity();
}
}
} catch (Exception ex) {
Log.e(LOGTAG, "try on create" + ex.getLocalizedMessage());
}
}
private void startAuthenticationActivity() {
Intent intent = new Intent(this,
ics.forth.withings.authentication.AuthenticationActivity.class);
startActivityForResult(intent, AUTHENTICATION_REQUEST);
}
AsyncTask<Object, Object, Object> getAccessTokenThread = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
accessToken = service
.getAccessToken(requestToken, new Verifier(""));
secret = accessToken.getSecret();
token = accessToken.getToken();
return null;
}
#Override
protected void onPostExecute(Object result) {
// authentication complete send the token,secret,userid, to python
datasource.createUser(token, secret, userId);
loadData();
};
};
}
UPDATE
OAuthService class is from Scribe
Token class is from Scribe
UserDataSource class is a DB Helper Class more here
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'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();