How to add user to SignalR Group in Android - java

i wanna add user to signalR group but it says failed.
my android code to add user in group as below
HubConnection connection = new HubConnection("http://www.planetskool.in/");
HubProxy proxy = connection.createHubProxy("ChatHub");
try {
//Log.d(TAG, "connection.start()...");
SignalRFuture<Void> awaitConnection = connection.start();
// Log.d(TAG, "started");
awaitConnection.get();
// Log.d(TAG, "got");
} catch (InterruptedException e) {
/// Log.e(TAG,"InterruptedException");
e.printStackTrace();
} catch (ExecutionException e) {
//Log.e(TAG, "ExecutionException");
e.printStackTrace();
}
SignalRFuture<Void> isGroupCreated2 = proxy.invoke("JoinGroup", loginUserInfoId);
Log.d("isGroupCreated", "isGroupCreated2 = " + proxy.invoke("JoinGroup", loginUserInfoId).isDone());
proxy.on("broadcastMessage",
new SubscriptionHandler1<String>() {
#Override
public void run(final String status) {
//getApplicationContext().runOnUiThread(new Runnable() {
//public void run() {
Log.d("SignalRResult=", status);
if(status.toUpperCase().equals("False".toUpperCase())) {
new SyncMessageFromServer().execute();
}
else {
new SyncGroupMessageFromServer().execute();
}
// }
//});
}
}
, String.class);
and the code in ChatHub in MVC Web Application is
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public void SendAll(string rUId, string message)
{
Clients.Group(rUId).broadcastMessage(message);
}
How can i make it work to send notification to particular user

Related

Android Studio get user data from Laravel database

I wish to retrieve data from the Laravel database and show it on the emulator of Android Studio. How can I access the data for the particular user like I view ipaddress/admin/users/1 ?
This is my getUser method in UserActivity.java:
private void getUser() {
String url = getString(R.string.api_server) + "/user";
new Thread(new Runnable() {
#Override
public void run() {
Http http = new Http(UserActivity.this, url);
http.setToken(true);
http.send();
runOnUiThread(new Runnable() {
#Override
public void run() {
Integer code = http.getStatusCode();
if (code == 200) {
try {
JSONObject response = new JSONObject(http.getResponse());
String name = response.getString("name");
String email = response.getString("email");
String gender = response.getString("gender");
tvName.setText(name);
tvEmail.setText(email);
tvCreated.setText(gender);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(UserActivity.this, "Error"+code, Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}

How to monitor LiveData hasActiveObservers()?

I have MyRepository that obtains a live feed from a server via a socket.
It provides its data to MyViewModel via a MutableLiveData object which can be observed from a Fragment.
To avoid wasting resources, I don't want MyRepository to be obtaining data from the server when there are no observers.
I'd like to know how to monitor MyRepository's MutableLiveData, so if there are no observers then MyRepository can stop retrieving data from the server. Similarly, if an observer is added, then data retrieval can (re)start.
Currently, I'm just using a basic Thread (see the createObserversMonitorThread() method) as the monitor:
public class MyRepository {
private static final String TAG = MyRepository.class.getSimpleName();
private MutableLiveData<String> mutableLiveData;
private Socket mSocket = null;
public MyRepository(Application application) {
mutableLiveData = new MutableLiveData<>();
createSocket();
createObserversMonitorThread();
}
private void createObserversMonitorThread() {
Thread thread = new Thread() {
#Override
public void run() {
try {
while (isAlive()) {
if (mutableLiveData.hasActiveObservers()) {
// We have observers, so connect to the server.
if (!mSocket.connected()) {
mSocket.connect();
}
}
else {
// We don't have observers, so disconnect from the server.
if (mSocket.connected()) {
mSocket.disconnect();
}
}
// Wait until next loop.
Thread.sleep(1000);
}
}
catch(Exception e) {
Log.e(TAG, "Exception", e);
}
}
};
thread.setName("MutableLiveData Observers Monitor");
thread.setPriority(1);
thread.setDaemon(true);
thread.start();
}
public LiveData<String> getMutableLiveData() {
return mutableLiveData;
}
/**
* This method posts retrieved data to mutableLiveData.
*/
private void createSocket() {
try {
mSocket = IO.socket(Constants.SERVER_URL);
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Connected.");
}
}).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
if (args[0] instanceof Exception) {
Log.e(TAG, "Connect error: ", (Exception)args[0]);
}
else {
Log.e(TAG, "Connect error: " + args[0]);
}
}
}).on(Socket.EVENT_RECONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Reconnected.");
}
}).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
if (args[0] instanceof Exception) {
Log.e(TAG, "Reconnect error: ", (Exception)args[0]);
}
else {
Log.e(TAG, "Reconnect error: " + args[0]);
}
}
}).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
#Override
public void call(Object... args) {
//Log.d(TAG, "Data received.");
String s = (String) args[0];
mutableLiveData.postValue(s);
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Disconnected.");
}
}).on(Socket.EVENT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
if (args[0] instanceof Exception) {
Log.e(TAG, "Error: ", (Exception)args[0]);
}
else {
Log.e(TAG, "Error: " + args[0]);
}
}
});
}
catch(Exception e) {
Log.e(TAG, "Could not create socket", e);
}
}
}
It works, but is there a better way?
UPDATE
Solution, thanks to EpicPandaForce's answer:
public class MyRepository {
private static final String TAG = MyRepository.class.getSimpleName();
private MutableLiveData<String> mutableLiveData;
private Socket mSocket = null;
public MyRepository(Application application) {
createSocket();
mutableLiveData = new MutableLiveData<String>() {
#Override
protected void onActive() {
super.onActive();
// Connect to server. This will (re)start data being posted on mutableLiveData.
if (!mSocket.connected()) {
mSocket.connect();
}
}
#Override
protected void onInactive() {
super.onInactive();
// Disconnect from server. This will stop data being posted on mutableLiveData.
if (mSocket.connected()) {
mSocket.disconnect();
}
}
};
}
public LiveData<String> getMutableLiveData() {
return mutableLiveData;
}
/**
* This method posts retrieved data to mutableLiveData.
*/
private void createSocket() {
// Same code as before.
}
}
You can use extends LiveData<T> or extends MutableLiveData<T> to get ahold of onActive() callback where you are notified if you have at least 1 active observer, and onInactive() callback when you went from 1 to 0 active observers.
That way you don't even need to ask for hasActiveObservers().

How to register device token to smack 4.2?

Following is my code and I want to get push notification when my device is offline or app is killed.
When my app is background I want to get notify by XMPP ejabberd server
IQ Class
class MyCustomIQ extends IQ {
String token = SharedPreferenceManager.getValue(getApplicationContext(), "DEVICE_TOKEN");
protected MyCustomIQ() {
super("query", "urn:xmpp:registernoti");
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.element("token", token);
xml.element("devicetpye", "android");
return xml;
}
}
On connected
#Override
public void connected(XMPPConnection connection) {
Log.e(TAG, "connected: ");
MyCustomIQ iq = new MyCustomIQ();
iq.setType(IQ.Type.set);
try {
abstractXMPPConnection.sendIqWithResponseCallback(iq, new StanzaListener() {
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
Log.e(TAG, "processStanza: " + packet.toString());
}
});
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Try following code for register device token on xmpp server
Register token stanza
<iq to="YourServer" type="set">
<register xmlns="https://android.googleapis.com/gcm" >
<key>API_KEY</key>
</register>
</iq>
1) way for register token
public void registerTokenTomod_gcm(final String deviceToken){
IQ iq=new IQ("register","https://android.googleapis.com/gcm") {
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("key",deviceToken);
xml.setEmptyElement();
return xml;
}
};
iq.setType(IQ.Type.set);
iq.setTo(AppConstants.CHAT_HOSTNAME);
debugLog("getpushDicsoInfo send stanza:"+iq.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(iq.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(iq);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
2) way to register token
public void registerTokenToXmpp(String deviceId,String deviceName,String deviceToken){
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(deviceToken);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceId);
FormField device_name = new FormField("device-name");
device_name.addValue(deviceName);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
UnRegister device token from server
private void unregisterToken(){
String deviceid="3524940..."; //sony
String tokenstring="GHkd7Ro2qtMg:XPA91bflkgklDeg..."; // sony
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(tokenstring);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceid);
FormField device_name = new FormField("device-name");
// device_name.addValue(devicename);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}

Data not stored into realm database

java.lang.IllegalStateException: Your Realm is opened from a thread
without a Looper and you provided a callback, we need a Handler to
invoke your callback
I'm Writing a code that will do in background- read from a text file(inside assets) and then placing them into a realm database.But i seem to get this error
"java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your
callback"
In my onCreate i have this
Realm.init(context);
realm = Realm.getDefaultInstance();
ParseInBackground task = new ParseInBackground();
task.execute();
and in the do-in-background task of AsyncTask i got this
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
handler.post(new Runnable() {
#Override
public void run() {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
and a Model class called ModelClass has this
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
Desperately in need of help.Thanks in advance
Check http://developer.android.com/reference/android/os/Handler.html and http://developer.android.com/reference/android/os/Looper.html
Basically Realm need a way to communicate with your thread when doing asyc query, on Android, naturally Looper and Handler is the way to go.
Check this for more sample code.
https://github.com/realm/realm-java/tree/master/examples/threadExample
You need to remove Handler.post(...) from within the execute callback.
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
I hope this helps.

Smack 4.1 No Response within reply timeout

I am using the following code in my android app:
Thread d = new Thread(new Runnable() {
#Override
public void run() {
SmackConfiguration.setDefaultPacketReplyTimeout(10000);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("admin", "password")
.setServiceName("192.168.0.200")
.setHost("192.168.0.200")
.setPort(5223).setSecurityMode(SecurityMode.ifpossible)
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
try {
conn2.connect();
conn2.login();
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("Gone fishing");
// Send the packet (assume we have an XMPPConnection instance called "con").
conn2.sendStanza(presence);
} catch (SmackException | IOException | XMPPException e) {
e.printStackTrace();
Log.d("TAG", e.toString());
}
ChatManager chatmanager = ChatManager.getInstanceFor(conn2);
Chat newChat = chatmanager.createChat("harsh#192.168.0.200");
try {
newChat.sendMessage("Howdy!");
}
catch (NotConnectedException e) {
e.printStackTrace();
}
}
});
d.start();
This is returning this error:
05-14 18:07:48.030: D/TAG(19470):
org.jivesoftware.smack.SmackException$NoResponseException: No response
received within reply timeout. Timeout was 10000ms (~10s). Used
filter: No filter used or filter was 'null'.
I have set up a local server at 192.168.0.200. Could anybody tell me what the problem is?
I am using these libraries:
I have successfully connected to local openfire server and logged in without SSL. Here is my code
public class NewClientActivity extends Activity {
EditText etUsername, etPassword;
Button bSubmit;
AbstractXMPPConnection mConnection;
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
Log.d("xmpp", "connected");
try {
SASLAuthentication.registerSASLMechanism(new SASLMechanism() {
#Override
protected void authenticateInternal(CallbackHandler callbackHandler) throws SmackException {
}
#Override
protected byte[] getAuthenticationText() throws SmackException {
byte[] authcid = toBytes('\u0000' + this.authenticationId);
byte[] passw = toBytes('\u0000' + this.password);
return ByteUtils.concact(authcid, passw);
}
#Override
public String getName() {
return "PLAIN";
}
#Override
public int getPriority() {
return 410;
}
#Override
public void checkIfSuccessfulOrThrow() throws SmackException {
}
#Override
protected SASLMechanism newInstance() {
return this;
}
});
mConnection.login();
} catch (XMPPException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this, "Incorrect username or password", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.d("xmpp", "authenticated");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this,"Logged in successfully...",Toast.LENGTH_LONG ).show();
}
});
}
#Override
public void connectionClosed() {
Log.d("xmpp", "connection closed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("xmpp", "cononection closed on error");
}
#Override
public void reconnectionSuccessful() {
Log.d("xmpp", "reconnection successful");
}
#Override
public void reconnectingIn(int i) {
Log.d("xmpp", "reconnecting in " + i);
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("xmpp", "reconnection failed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_client);
findViews();
}
private void findViews() {
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] params = new String[]{etUsername.getText().toString(), etPassword.getText().toString()};
new Connect().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}
});
}
class Connect extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
XMPPTCPConnectionConfiguration config = null;
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setServiceName("192.168.1.60").setHost("192.168.1.60")
.setDebuggerEnabled(true)
.setPort(5222)
.setUsernameAndPassword(params[0], params[1])
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false);
config = builder.build();
mConnection = new XMPPTCPConnection(config);
try {
//mConnection.setPacketReplyTimeout(10000);
mConnection.addConnectionListener(connectionListener);
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
}
}
I just removed .setPort from my request and it worked :
private class MyLoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// Create a connection to the jabber.org server.
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setUsernameAndPassword(USERNAME, PASSWORD)
.setHost(HOST)
//.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(HOST)
.setDebuggerEnabled(true) // to view what's happening in detail
.build();
AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
conn1.setPacketReplyTimeout(30000);
try {
conn1.connect();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
}
}
Try this :
public static void main(String[] args) throws IOException, XMPPException, SmackException, NoSuchAlgorithmException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setServiceName("olx.intr")
.setDebuggerEnabled(true)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setHost("10.2.2.107")
.setPort(5222)
.setUsernameAndPassword("dhiren","olxindia")
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.connect();
SASLMechanism mechanism = new SASLDigestMD5Mechanism();
SASLAuthentication.registerSASLMechanism(mechanism);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");
try {
conn2.login();
}catch (Exception e){
e.printStackTrace();
}
boolean authenticated = conn2.isAuthenticated();
System.out.println(authenticated);
}

Categories