SignalR Android client not Hitting OnConnected method in Server - android

I have the following TestHub class in my server.
public class TestHub:Hub {
public override Task OnConnected() {
//do some work here
return base.OnConnected();
}
}
and my android client uses the following code to start negotiating with server.
//set serverUrl, device_id, logger, serverHub
Platform.loadPlatformComponent(new AndroidPlatformComponent());
HubConnection connection = new HubConnection(serverUrl, "device_id="+device_id, false, logger);
HubProxy proxy = connection.createHubProxy(serverHub);
proxy.subscribe(this);
proxy.on("test", new SubscriptionHandler1<String>() {
#Override
public void run(String x) {
System.out.println(x);
}
}, String.class);
ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
I'm trying to do some work in server OnConnected() method but it won't hit. i have signalr connection successfully but i want to do some stuff in OnConnected() method. what should i do?

Related

Android: wait subthread

I want to wait for the completion of a sub-thread to determine the login status. But I'm not familiar with how to write internal classes, so I'd like to ask how to write code to wait for a child thread to finish execution in the login function.
public class LoginDataSource {
static LoggedInUser loggedUser = new LoggedInUser();
public Result<LoggedInUser> login(String username, String password) {
try {
// TODO: handle loggedInUser authentication
loginMyBlog(username, password, loggedUser);
if (loggedUser.isLogStatue()) {
return new Result.Success<>(loggedUser);
} else {
return new Result.Failed("pass incorrect");
}
} catch (Exception e) {
return new Result.Error(new IOException("Error logging in", e));
}
}
public void logout() {
// TODO: revoke authentication
}
private void loginMyBlog(String usernames, String passwords, LoggedInUser userAuth) {
new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
// Code for sending network requests
//...
//Code to determine if the login is successful
try {
Response response = client.newCall(request).execute();
final String responseData = response.body().string();
JSONObject jsonObject = JSONObject
.parseObject(responseData);
String code = jsonObject.getString("code");
if (code.equals("20000")){
// login success
JSONObject dataObject = JSONObject.parseObject(jsonObject.getString("data"));
userAuth.setId(dataObject.getInteger("id"));
userAuth.setIntro(dataObject.getString("intro"));
userAuth.setLogStatue(true);
Log.d("test", "登录成功"+userAuth);
}else if (code.equals("51000")){
// login failed
userAuth.setLogStatue(false);
}
} catch (IOException e) {
e.printStackTrace();
// network err
}
}
}).start();
}
}
Thanks.

Not able to send message using smack Android

i am trying to send message to client but always getting this exception: org.jivesoftware.smack.SmackException$NotConnectedException: Client is not, or no longer, connected.
Following are my code to send message:
ChatManager chatMngr = ChatManager.getInstanceFor(connection);
Chat chat = chatMngr.createChat(toName + "#stag-api.artistaloud.com", FrgChatRoom.this);
try {
chat.sendMessage(txtChatMsg.getText().toString().trim());
} catch (Exception e) {
e.printStackTrace();
}
When i am relogin before send the message. its working fine...please reply..
this exception occurs while you are not connected with Xmpp server.
first insure that are you connect with server or not?.and for get connected with server with asmack libs use this code:
private class ConnectToXmpp extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ConnectionConfiguration config = new ConnectionConfiguration( server_host, SERVER_PORT);
XMPPConnection m_connection = new XMPPConnection(config);
try {
SASLAuthentication.supportSASLMechanism("PLAIN");
config.setSASLAuthenticationEnabled(true);
m_connection.connect();
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
and now you can execute this as new ConnectToXmpp().execute();
and for sending message you have to create chat like:
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat("jsmith#jivesoftware.com", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Howdy!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
and Chat.sendMessage(String) method is a convenience method that creates a Message object, sets the body using the String parameter, then sends the message.
and then use this code sniipet for send message:
Message newMessage = new Message();
newMessage.setBody("Howdy!");
message.setProperty("favoriteColor", "red");
newChat.sendMessage(newMessage);
and for more information see this link.

Signalr with android client

Hi I'm new to Signalr and I want to develop android native client application for communicate with signalr server. So I follow "whathecode" article and still i'm not able to connect to server. Anyone can give me some sample project or example.Its big help for me. Thank you.
public void connect(){
HubConnection con = new HubConnection(Uri.parse("http://10.0.2.2:3227/").toString());
HubProxy hub = con.createHubProxy("MyHub1");
con.start();
try {
hub.invoke( "Send", "user", "Hello world!" ).get();
} catch (InterruptedException e) {
// Handle ...
} catch (ExecutionException e) {
// Handle ...
}
}
I face same issue like you but it resolved by adding 3227 part to allow all connection from it in my windows firewall settings .
I also suggest instead of creating localhost use some ip and create SignalR server, after that it should work fine.
private void createConnections() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "http://192.168.0.63/SignalRServerApp/signalr";
final HubConnection connection = new HubConnection(host, false);
final HubProxy hp = connection.createHubProxy("MyHubController");
Toast.makeText(getActivity(), SampleWork.getStringData(), Toast.LENGTH_LONG).show();
System.out.println(SampleWork.getStringData());
SignalRFuture<Void> awaitConnection = connection.start();
try {
EditText text = (EditText) getActivity()
.findViewById(R.id.text);
String data = text.getText().toString();
awaitConnection.get();
try {
hp.invoke("ReceiveData", data);
} catch (Exception e) {
System.out.println("Error");
}
//Calling a server method named "Acknowledge"
hp.on("Acknowledge", new SubscriptionHandler1<String>() {
#Override
public void run(final String p1) {
//Here u gets the response from server
}
}, String.class);
System.out.println("Test");
} catch (Exception e) {
e.printStackTrace();
}
}`enter code here`

Getting bad request 400 error using asmack in android

I am trying to register a new user using my XMPP client using asmack library in Android on ejabberd server. The problem is that I am getting following error & the user is not being created on the server:
bad-request(400)
at org.jivesoftware.smack.AccountManager.createAccount(AccountManager.java:243)
at in.ui.MainActivity$1$1$1.run(MainActivity.java:316)
at java.lang.Thread.run(Thread.java:841)
Following is the code:
_xmppUsername = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_ID);
_xmppPassword = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_PASSWORD);
_xmppHost = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_HOST);
try {
_xmppPortNo = Integer.parseInt (XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_PORT));
} catch (Exception e) {
e.printStackTrace ();
Log.e (TAG, e.getMessage ());
}
_xmppServiceName = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_SERVICE_NAME);
ConnectionConfiguration conConfig = new ConnectionConfiguration (_xmppHost, _xmppPortNo, _xmppServiceName);
_xmppConnection = new XMPPConnection (conConfig);
if (!_xmppConnection.isAuthenticated ()) {
login ();
}
/*
* If connection has not been established or had been established &
* broken again then login
*/
#Override
public void onShow (final DialogInterface dialog) {
Button positiveButton = _dlgRegistration.getButton (DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
// Creating registration thread
new Thread (new Runnable () {
#Override
public void run () {
String clientID = null;
String password = null;
clientID = "user" + XMPP_SERVICE_NAME;
try {
// Getting hash password from UUID
password = "password";
Log.i (TAG, clientID + password);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace ();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace ();
}
}
AccountManager manager = _xmppConnection.getAccountManager ();
try {
// Creating account on the server
manager.createAccount (clientID, password, attr);
}
} catch (XMPPException e) {
e.printStackTrace ();
}
}
}).start ();
}
});
The problem was this line clientID = "user" + XMPP_SERVICE_NAME; where I shouldn't have been appending Domain or Service Name after "user".

Listing Google Drive File on Android using Files.List() API

Currently i need to make an application that can list all of Google Drive file.
i already did the account choosing and oauth process, an already get the token. but when i try to use API call to list all my file on Google Drive (By using drive.files.list) i didn't get any result, the arraylist of files which is supposed to hold all the file is still empty. i also got error :
java.net.unknownHostException www.googleapis.com cannot be resolved
this is my code :
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", got.name);
editor.commit();
account=got;
amf=accMgr.getAuthToken(account, authTokenType, true,
new AccountManagerCallback<Bundle>(){
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle result;
Intent i;
String token;
Drive a;
result = arg0.getResult();
if (result.containsKey(accMgr.KEY_INTENT)) {
i = (Intent)result.get(accMgr.KEY_INTENT);
if (i.toString().contains("GrantCredentialsPermissionActivity")) {
// Will have to wait for the user to accept
// the request therefore this will have to
// run in a foreground application
cbt.startActivity(i);
} else {
cbt.startActivity(i);
}
}
else if (result.containsKey(accMgr.KEY_AUTHTOKEN)) {
accessProtectedResource.setAccessToken(result
.getString(accMgr.KEY_AUTHTOKEN));
buildService(result
.getString(accMgr.KEY_AUTHTOKEN),API_KEY);
/*else {
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);*/
/*
* work with token
*/
// Remember to invalidate the token if the web service rejects it
// if(response.isTokenInvalid()){
// accMgr.invalidateAuthToken(authTokenType, token);
// }
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, handler);
}
private void buildService(final String authToken, final String ApiKey) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(ApiKey);
driveRequest.setOauthToken(authToken);
}
});
System.out.println(authToken);
service= b.build();
List<File> a=new ArrayList<File>();
try {
a = retrieveDriveFile(service);
System.out.println(a.size());
File c=a.get(0);
TextView ad=(TextView) findViewById(R.id.test);
ad.setText(c.getOriginalFilename());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> retrieveDriveFile(Drive service) throws IOException{
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error ssoccurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
This would typically happen if you don't have a working internet connection on your device.
Also don't forget to add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
This could happen also if you are behind a proxy. If that's the case please have a look at this question.
If you want to get all the file from Goolge Drive. Assume that you have already done the Account Choosing process and creating Drive (Drive mService) etc.
Now Under Button Click Event call this function
ButtonClickEvent
{
GetDriveData();
}
// FUNCTION TO RETRIEVE GOOGLE DRIVE DATA
private void GetDriveData()
{
private List<File> mResultList;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.List request = null;
do
{
try
{
request = f1.list();
request.setQ("trashed=false");
com.google.api.services.drive.model.FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();//Calling to Populate Data to the List
}
});
t.start();
}
//Populating Retrieved data to List
private void populateListView()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mFileArray = new String[mResultList.size()];
int i = 0;
for(File tmp : mResultList)
{
//System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
button2.setText("yes");
}
});
}

Categories

Resources