Guest User

Untitled

a guest
May 24th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.86 KB | None | 0 0
  1. compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.3-SNAPSHOT'
  2. compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.3-SNAPSHOT'
  3.  
  4. package net.kindows.chitchat;
  5.  
  6. import android.app.ProgressDialog;
  7. import android.content.Intent;
  8. import android.content.pm.ActivityInfo;
  9. import android.os.Bundle;
  10. import android.os.Handler;
  11. import android.support.v7.app.AppCompatActivity;
  12. import android.util.Log;
  13. import android.view.View;
  14. import android.view.WindowManager;
  15. import android.widget.Button;
  16. import android.widget.EditText;
  17. import android.widget.TextView;
  18.  
  19. import com.google.gson.JsonObject;
  20. import com.google.gson.JsonParser;
  21. import com.pixplicity.easyprefs.library.Prefs;
  22.  
  23. import net.kindows.SplashScreen;
  24. import net.kindows.common.ApplicationLoader;
  25. import net.kindows.common.utils;
  26. import net.kindows.intlPhone.IntlPhoneInput;
  27.  
  28. import org.eclipse.paho.android.service.MqttAndroidClient;
  29. import org.eclipse.paho.client.mqttv3.IMqttActionListener;
  30. import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
  31. import org.eclipse.paho.client.mqttv3.IMqttToken;
  32. import org.eclipse.paho.client.mqttv3.MqttCallback;
  33. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  34. import org.eclipse.paho.client.mqttv3.MqttException;
  35. import org.eclipse.paho.client.mqttv3.MqttMessage;
  36.  
  37. import butterknife.Bind;
  38. import butterknife.ButterKnife;
  39. import de.keyboardsurfer.android.widget.crouton.Crouton;
  40.  
  41. import static net.kindows.common.ApplicationLoader._toast;
  42.  
  43. public class LoginActivity extends AppCompatActivity implements MqttCallback {
  44.  
  45. private static final String TAG = "LoginActivity";
  46. private static final int REQUEST_SIGNUP = 0;
  47. private static final int REQUEST_PAS_RESET = 1;
  48.  
  49. private static final Integer LOGGED_OUT = 0;
  50. private static final Integer LOGGING_IN = 1;
  51. private static final Integer WAITING_FOR_SING_IN_ACK = 2;
  52. private static final Integer LOGGED_IN = 3;
  53. private static final Integer VERIFICATION_FAILED = 4;
  54.  
  55. @Bind(R.id.input_password)
  56. EditText _passwordText;
  57. @Bind(R.id.btn_login)
  58. Button _loginButton;
  59. @Bind(R.id.link_signup)
  60. TextView _signupLink;
  61.  
  62. @Bind(R.id.my_phone_input)
  63. IntlPhoneInput _phoneInputView;
  64. String sUserName = null;
  65. String sPassword = null;
  66. String sDestination = null;
  67. String sMessage = null;
  68.  
  69. private Integer state;
  70. private Handler han = new Handler();
  71. private MqttConnectOptions connOpt;
  72. private ProgressDialog _progressDialog;
  73. /*
  74. MQTT mqtt = null;
  75.  
  76. FutureConnection connection = null;*/
  77. private boolean isMinimized = false;
  78. private String clientId;
  79. private Handler loginAgain = new Handler();
  80. private Handler timeout;
  81. private MqttAndroidClient client;
  82.  
  83. @Override
  84. public void onCreate(Bundle savedInstanceState) {
  85. super.onCreate(savedInstanceState);
  86. setContentView(R.layout.activity_login);
  87. ButterKnife.bind(this);
  88. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
  89. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  90. //connect();
  91. _loginButton.setEnabled(false);
  92.  
  93. // _phoneInputView.setNumber(ApplicationLoader.getSim1number(LoginActivity.this));
  94. _phoneInputView.setOnValidityChange(new IntlPhoneInput.IntlPhoneInputListener() {
  95. @Override
  96. public void done(View view, boolean isValid) {
  97. if (isValid) {
  98. _loginButton.setEnabled(true);
  99. } else _loginButton.setEnabled(false);
  100. }
  101. });
  102. _loginButton.setOnClickListener(new View.OnClickListener() {
  103.  
  104. @Override
  105. public void onClick(View v) {
  106. if (!ApplicationLoader.isConnected(LoginActivity.this, true)) {
  107. } else login();
  108. }
  109. });
  110.  
  111. _signupLink.setOnClickListener(new View.OnClickListener() {
  112.  
  113. @Override
  114. public void onClick(View v) {
  115. // Start the Signup activity
  116. Prefs.putInt(getString(R.string.key_reset_pass), 2);
  117. Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
  118. startActivityForResult(intent, REQUEST_SIGNUP);
  119. }
  120. });
  121. state = LOGGED_OUT;
  122. connOpt = new MqttConnectOptions();
  123. connOpt.setCleanSession(true);
  124. connOpt.setKeepAliveInterval(30);
  125. connOpt.setCleanSession(true);
  126.  
  127. clientId = ApplicationLoader.getClientId(LoginActivity.this);
  128. client = new MqttAndroidClient(this, "tcp://104.131.50.64:1883", clientId, MqttAndroidClient.Ack.AUTO_ACK);//this,"tcp://104.131.50.64:1883", "app1", null);
  129.  
  130. }
  131.  
  132. @Override
  133. protected void onStop() {
  134. super.onStop();
  135. isMinimized = true;
  136. // super.onDestroy();
  137. try {
  138.  
  139. client.close();
  140. } catch (Exception e) {
  141. // client.unregisterResources();
  142. e.printStackTrace();
  143. }
  144.  
  145. Crouton.cancelAllCroutons();
  146. loginAgain.removeCallbacks(null);
  147. han.removeCallbacks(null);
  148.  
  149. }
  150.  
  151. @Override
  152. protected void onStart() {
  153. super.onStart();
  154. // Do not go to splash screen if came from signup activity
  155. if (isMinimized && Prefs.getBoolean(getString(R.string.show_splash), true)) {
  156. isMinimized = false;
  157. han.removeCallbacks(null);
  158. startActivity(new Intent(this, SplashScreen.class));
  159. finish();
  160. }
  161. Prefs.putBoolean(getString(R.string.show_splash), true);
  162. if (utils.getLoginState_login()) {
  163. han.removeCallbacks(null);
  164. utils._startActivity(this, MainActivity.class);
  165. finish();
  166. }
  167. }
  168.  
  169. @Override
  170. protected void onResume() {
  171. super.onResume();
  172.  
  173. if (utils.getLoginState_login()) {
  174. han.removeCallbacks(null);
  175. utils._startActivity(this, MainActivity.class);
  176. finish();
  177.  
  178. }
  179.  
  180. ApplicationLoader.isConnected(this, true);
  181.  
  182. }
  183.  
  184. public void login() {
  185. Log.d(TAG, getString(R.string.login));
  186. _toast(getString(R.string.logging_in), LoginActivity.this);
  187.  
  188. try {
  189. client.close();
  190. } catch (Exception e) {
  191. e.printStackTrace();
  192. }
  193.  
  194. try {
  195. client.close();
  196. } catch (Exception e) {
  197. e.printStackTrace();
  198. }
  199.  
  200. // Disable login button for 5 secs
  201. final boolean lastLoginState = _loginButton.isEnabled();
  202. _loginButton.setEnabled(false);
  203. loginAgain.postDelayed(new Runnable() {
  204. @Override
  205. public void run() {
  206. _loginButton.setEnabled(lastLoginState);
  207. }
  208. }, 5000);
  209.  
  210. _progressDialog = new ProgressDialog(LoginActivity.this,
  211. R.style.AppTheme_Dark_Dialog);
  212. // String phone = _phoneText.getText().toString();
  213. String password = _passwordText.getText().toString();
  214. String numb = _phoneInputView.getNumber().replace("+", "");
  215. connectMQTT(numb, password);
  216. _progressDialog.setIndeterminate(true);
  217. _progressDialog.setMessage("Authenticating...");
  218. _progressDialog.show();
  219.  
  220. han.postDelayed(
  221. new Runnable() {
  222. public void run() { // On complete call either onLoginSuccess or onLoginFailed
  223. //onLoginSuccess();
  224. onLoginFailed();
  225. _progressDialog.dismiss();
  226. }
  227. }, ApplicationLoader.timeOUT);
  228. }
  229.  
  230. private void publish2MQQT(MqttAndroidClient client1, String topic, String msg) throws MqttException {
  231. if (client1 != null) {
  232.  
  233. MqttMessage msg2 = new MqttMessage();
  234. msg2.setPayload(msg.getBytes());
  235. client1.publish(topic, msg2, this, new IMqttActionListener() {
  236. @Override
  237. public void onSuccess(IMqttToken asyncActionToken) {
  238. // _sendErrorLog("on sucess of publish");
  239. }
  240.  
  241. @Override
  242. public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  243. // _sendErrorLog("on fail of publish e= " + exception.getMessage());
  244. _progressDialog.dismiss();
  245. _toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
  246. }
  247. });
  248.  
  249. // Log.e("mqtt ", "published " + msg);
  250. }
  251.  
  252. }
  253.  
  254. private void _sendErrorLog(String s) {
  255. Log.e("LOG", s);
  256. }
  257.  
  258. private void connectMQTT(final String user, final String pass) {
  259. Log.e("connectMQTT", "1");
  260.  
  261. try {
  262. connOpt.setUserName(user);
  263. connOpt.setPassword(pass.toCharArray());
  264. _sendErrorLog("on connteing with " + user + " " + pass);
  265. client.connect(connOpt, this, new IMqttActionListener() {
  266. @Override
  267. public void onSuccess(IMqttToken asyncActionToken) {
  268. _sendErrorLog("on success of connect");
  269. try {
  270. client.subscribe("astr/app/iremote/" + user.replace("+", ""), 0, this, new IMqttActionListener() {
  271. @Override
  272. public void onSuccess(IMqttToken asyncActionToken) {
  273. _sendErrorLog("on sucess of subscribe");
  274.  
  275. // TODO: Implement your own authentication logic here.
  276. JsonObject msg = new JsonObject();
  277. msg.addProperty("u", user);
  278. msg.addProperty("P", pass);
  279.  
  280. sUserName = user;
  281. sPassword = pass;
  282. sDestination = "astr/admin/signin";
  283. sMessage = msg.toString();
  284. state = LOGGING_IN;
  285. try {
  286. Log.e("register", "publishing signin message");
  287. if (client == null) {
  288. Log.e("register", "publishing register message client is null");
  289.  
  290. }
  291. publish2MQQT(client, sDestination, sMessage);
  292. state = WAITING_FOR_SING_IN_ACK;
  293. } catch (MqttException e) {
  294. e.printStackTrace();
  295. Log.e("register", "got exception in publish " + e.toString());
  296. _progressDialog.dismiss();
  297. _toast(e.getMessage(), LoginActivity.this);
  298.  
  299. }
  300. }
  301.  
  302. @Override
  303. public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  304. _sendErrorLog("on failure of subscribe " + exception.getMessage());
  305. _progressDialog.dismiss();
  306. _toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
  307.  
  308. }
  309. });
  310. // client.subscribe("astr/app/iremote/" + _num_2b_verified.replace("+", ""));
  311. } catch (MqttException | NullPointerException e) {
  312. e.printStackTrace();
  313. }
  314.  
  315. }
  316.  
  317. @Override
  318. public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
  319. _sendErrorLog("on failure of connect" + exception.getMessage());
  320. han.removeCallbacks(null);
  321. try {
  322. _progressDialog.dismiss();
  323. } catch (Exception e) {
  324. e.printStackTrace();
  325. }
  326. _toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
  327.  
  328. }
  329. });
  330. client.setCallback(this);
  331.  
  332. } catch (MqttException e) {
  333. e.printStackTrace();
  334. Log.e("connectMQTT", "got exception :: " + e.toString());
  335. }
  336.  
  337. }
  338.  
  339. @Override
  340. public void connectionLost(Throwable throwable) {
  341. Log.e("connection", "lost");
  342. //connectMQTT();
  343.  
  344. }
  345.  
  346. @Override
  347. protected void onDestroy() {
  348. super.onDestroy();
  349. try {
  350. client.close();
  351. } catch (Exception e) {
  352. e.printStackTrace();
  353. }
  354.  
  355. }
  356.  
  357. @Override
  358. public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
  359.  
  360. String msgRecived = new String(mqttMessage.getPayload());
  361. /* Log.e("message arrived", "-------------------------------------------------");
  362. Log.e("message arrived", "| Topic:" + s);*/
  363. Log.e("message arrived", "| Message: " + msgRecived);
  364. /*Log.e("message arrived" , "-------------------------------------------------");*/
  365.  
  366. if (state.equals(WAITING_FOR_SING_IN_ACK)) {
  367.  
  368. han.removeCallbacks(null);
  369. JsonParser jp = new JsonParser();
  370. JsonObject reply = (JsonObject) jp.parse(msgRecived);
  371. if (reply.get("s").getAsInt() == 200) {
  372. _toast(getString(R.string.logged_in), LoginActivity.this);
  373. _progressDialog.dismiss();
  374. _phoneInputView.setVisibility(View.GONE);
  375.  
  376. _passwordText.setVisibility(View.VISIBLE);
  377. _loginButton.setText(R.string.logged_in);
  378. _loginButton.setEnabled(true);
  379. state = LOGGED_IN;
  380. utils.storeLoginState(true, sUserName, sPassword);
  381. try {
  382. client.close();
  383. } catch (Exception e) {
  384. e.printStackTrace();
  385. }
  386.  
  387. state = LOGGED_IN;
  388. han.removeCallbacks(null);
  389. try {
  390. client.close();
  391. } catch (Exception e) {
  392. e.printStackTrace();
  393. }
  394. startActivity(new Intent(this, MainActivity.class));
  395. //finish();
  396.  
  397. } else {
  398. state = VERIFICATION_FAILED;
  399. utils.storeLoginState(false, "", "");
  400. onLoginFailed();
  401. }
  402. }
  403.  
  404. }
  405.  
  406. @Override
  407. public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
  408.  
  409. }
  410.  
  411.  
  412. @Override
  413. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  414. if (requestCode == REQUEST_SIGNUP) {
  415. if (resultCode == RESULT_OK) {
  416.  
  417. // TODO: Implement successful signup logic here
  418. // By default we just finish the Activity and log them in automatically
  419. this.finish();
  420. }
  421. }
  422. }
  423.  
  424. @Override
  425. public void onBackPressed() {
  426. // Disable going back to the MainActivity
  427. moveTaskToBack(true);
  428. }
  429.  
  430. public void onLoginFailed() {
  431. // ApplicationLoader._toast("Login failed",LoginActivity.this);
  432. _toast(getString(R.string.log_in_failed), LoginActivity.this);
  433. _passwordText.setVisibility(View.VISIBLE);
  434. _phoneInputView.setVisibility(View.VISIBLE);
  435. _loginButton.setEnabled(false);
  436.  
  437. // Enable Login after 5000 ms with editing the number
  438. loginAgain.postDelayed(new Runnable() {
  439. @Override
  440. public void run() {
  441. _loginButton.setEnabled(_phoneInputView.isValid());
  442. }
  443. }, 5000);
  444. }
  445.  
  446. @Override
  447. public void onPause() {
  448. super.onPause();
  449.  
  450. //disconnect();
  451. }
  452.  
  453. public void resetPass(View view) {
  454. // Start the Signup activity
  455. Prefs.putInt(getString(R.string.key_reset_pass), 1);
  456. Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
  457. startActivityForResult(intent, REQUEST_PAS_RESET);
  458. }
  459.  
  460. }
Add Comment
Please, Sign In to add comment