MainActivity.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. package de.tudarmstadt.informatik.hostage.ui;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.client.HttpClient;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.impl.client.DefaultHttpClient;
  11. import org.apache.http.util.EntityUtils;
  12. import org.json.JSONObject;
  13. import android.app.Activity;
  14. import android.app.ActivityManager;
  15. import android.app.ActivityManager.RunningServiceInfo;
  16. import android.content.BroadcastReceiver;
  17. import android.content.ComponentName;
  18. import android.content.Context;
  19. import android.content.Intent;
  20. import android.content.IntentFilter;
  21. import android.content.ServiceConnection;
  22. import android.content.SharedPreferences;
  23. import android.content.SharedPreferences.Editor;
  24. import android.net.ConnectivityManager;
  25. import android.os.AsyncTask;
  26. import android.os.Bundle;
  27. import android.os.Handler;
  28. import android.os.IBinder;
  29. import android.support.v4.content.LocalBroadcastManager;
  30. import android.util.Log;
  31. import android.view.GestureDetector;
  32. import android.view.GestureDetector.SimpleOnGestureListener;
  33. import android.view.Menu;
  34. import android.view.MenuItem;
  35. import android.view.MotionEvent;
  36. import android.view.View;
  37. import android.view.View.OnTouchListener;
  38. import android.view.animation.Animation;
  39. import android.view.animation.AnimationUtils;
  40. import android.widget.AdapterView;
  41. import android.widget.AdapterView.OnItemClickListener;
  42. import android.widget.CheckBox;
  43. import android.widget.ImageView;
  44. import android.widget.ListView;
  45. import android.widget.TextView;
  46. import android.widget.ToggleButton;
  47. import android.widget.ViewAnimator;
  48. import de.tudarmstadt.informatik.hostage.HoneyService;
  49. import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
  50. import de.tudarmstadt.informatik.hostage.R;
  51. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  52. import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver;
  53. import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver.Receiver;
  54. import de.tudarmstadt.informatik.hostage.logging.Logger;
  55. /**
  56. * MainActivity is the central activity for the GUI of the application.
  57. * MainActivity is launched when the application is first started. It shows the
  58. * user: <br>
  59. * - information about the network<br>
  60. * - light indicators for recorded attacks on each protocol<br>
  61. * - amount of attacks on each protocols<br>
  62. * The user can start and stop services.
  63. *
  64. * @author Mihai Plasoianu
  65. * @author Lars Pandikow
  66. * @author Wulf Pfeiffer
  67. */
  68. public class MainActivity extends Activity implements Receiver {
  69. // String constants for whole application
  70. /**
  71. * Used for Broadcast between service and GUI. String:
  72. * "de.tudarmstadt.informatik.hostage.BROADCAST"
  73. */
  74. public static final String BROADCAST = "de.tudarmstadt.informatik.hostage.BROADCAST";
  75. /**
  76. * Used to store session related data in a SharedPrefereces. String:
  77. * "de.tudarmstadt.informatik.hostage.SESSION_DATA"
  78. */
  79. public static final String SESSION_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
  80. public static final String LISTENER = "_LISTENER";
  81. public static final String HANDLER_COUNT = "_HANDLER_COUNT";
  82. public static final String SSID = "SSID";
  83. public static final String BSSID = "BSSID";
  84. public static final String INTERNAL_IP = "INTERNAL_IP";
  85. public static final String EXTERNAL_IP = "EXTERNAL_IP";
  86. /**
  87. * Flag for root acces. True if phone has root acces, else false.
  88. */
  89. public static boolean isRooted = false;
  90. /**
  91. * Flag for porthack. True if porthack is installed, else false.
  92. */
  93. public static boolean porthackInstalled = false;
  94. /**
  95. * Integer representing a grey light.
  96. */
  97. public static final int LIGHT_GREY = 0x01;
  98. /**
  99. * Integer representing a green light.
  100. */
  101. public static final int LIGHT_GREEN = 0x02;
  102. /**
  103. * Integer representing a red light.
  104. */
  105. public static final int LIGHT_RED = 0x03;
  106. /**
  107. * Integer representing a yellow light.
  108. */
  109. public static final int LIGHT_YELLOW = 0x04;
  110. private static Context context;
  111. public LogResultReceiver logResultReceiver;
  112. private HoneyService mService;
  113. private boolean serviceBound;
  114. private SharedPreferences sessionPref;
  115. private Editor sessionEditor;
  116. // variables for the swipe animation
  117. private ViewAnimator viewAnimator;
  118. private GestureDetector gestureDetector;
  119. private Animation animFlipInLR;
  120. private Animation animFlipOutLR;
  121. private Animation animFlipInRL;
  122. private Animation animFlipOutRL;
  123. private ListView listView;
  124. private ListViewAdapter adapter;
  125. private String protocolClicked;
  126. private boolean isBssidSeen = false;
  127. @Override
  128. protected void onCreate(Bundle savedInstanceState) {
  129. super.onCreate(savedInstanceState);
  130. MainActivity.context = getApplicationContext(); // set context
  131. logResultReceiver = new LogResultReceiver(new Handler());
  132. setContentView(R.layout.activity_main);
  133. // Create dynamic view elements
  134. initViewAnimator();
  135. initListView();
  136. // Initialize Class variables
  137. sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
  138. sessionEditor = sessionPref.edit();
  139. checkRootAndPorthack();
  140. }
  141. @Override
  142. public boolean onCreateOptionsMenu(Menu menu) {
  143. getMenuInflater().inflate(R.menu.main, menu);
  144. return true;
  145. }
  146. @Override
  147. public boolean onOptionsItemSelected(MenuItem item) {
  148. // Handle item selection
  149. switch (item.getItemId()) {
  150. case R.id.action_settings:
  151. startActivity(new Intent(this, SettingsActivity.class));
  152. break;
  153. case R.id.action_about:
  154. startActivity(new Intent(this, AboutActivity.class));
  155. break;
  156. default:
  157. }
  158. return super.onOptionsItemSelected(item);
  159. }
  160. @Override
  161. protected void onStart() {
  162. super.onStart();
  163. // Register Broadcast Receiver
  164. registerReceiver();
  165. registerNetReceiver();
  166. logResultReceiver.setReceiver(this);
  167. // Bind service if running, else check for connection change and delete
  168. // sessionData
  169. if (isServiceRunning()) {
  170. bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
  171. } else {
  172. String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
  173. String bssid_new = HelperUtils.getBSSID(this);
  174. if (bssid_new == null || !bssid_new.equals(bssid_old)) {
  175. deleteSessionData();
  176. }
  177. }
  178. // Update UI
  179. updateUI();
  180. updateConnectionInfText();
  181. }
  182. @Override
  183. protected void onStop() {
  184. // Unbind running service
  185. if (isServiceRunning()) {
  186. unbindService(mConnection);
  187. }
  188. // Unregister Broadcast Receiver
  189. unregisterNetReceiver();
  190. unregisterReceiver();
  191. logResultReceiver.setReceiver(null);
  192. super.onStop();
  193. }
  194. @Override
  195. protected void onDestroy() {
  196. super.onDestroy();
  197. // If service not running delete session data
  198. if (!isServiceRunning()) {
  199. deleteSessionData();
  200. }
  201. }
  202. @Override
  203. public void onReceiveResult(int resultCode, Bundle resultData) {
  204. isBssidSeen = resultData.getBoolean("result");
  205. }
  206. /**
  207. * Called when User presses on/off button.
  208. *
  209. * @param view
  210. */
  211. public void buttonOnOffClick(View view) {
  212. if (((ToggleButton) view).isChecked()) {
  213. if (isParanoid()) {
  214. protocolClicked = "PANIC";
  215. } else {
  216. protocolClicked = "SMB";
  217. }
  218. startAndBind();
  219. } else {
  220. mService.stopListeners();
  221. stopAndUnbind();
  222. }
  223. }
  224. /**
  225. * Starts the ViewLog activity, when the Button is pressed.
  226. *
  227. * @see ViewLog
  228. * @param view
  229. * View elements which triggers the method call.
  230. */
  231. public void showLog(View view) {
  232. startActivity(new Intent(this, ViewLog.class));
  233. }
  234. public void startPlayGround(View view) {
  235. startActivity(new Intent(this, PlayGroundActivity.class));
  236. }
  237. /**
  238. * If mobile phone is connected to a wireless network starts the background
  239. * service ands binds itself to it. Else notifies the user that service
  240. * could not be started.
  241. */
  242. private void startAndBind() {
  243. startService(getServiceIntent());
  244. bindService();
  245. }
  246. /**
  247. * Binds service to Activity
  248. *
  249. * @see HoneyService
  250. */
  251. private void bindService() {
  252. bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
  253. serviceBound = true;
  254. }
  255. /**
  256. * Stops service and unbinds it.
  257. *
  258. * @see HoneyService
  259. */
  260. private void stopAndUnbind() {
  261. unbindService();
  262. stopService(getServiceIntent());
  263. }
  264. /**
  265. * Unbinds service.
  266. *
  267. * @see HoneyService
  268. */
  269. private void unbindService() {
  270. unbindService(mConnection);
  271. serviceBound = false;
  272. }
  273. /**
  274. * Connection to bind the background service
  275. *
  276. * @see HoneyService
  277. */
  278. private ServiceConnection mConnection = new ServiceConnection() {
  279. /**
  280. * After the service is bound, check which has been clicked and start
  281. * it.
  282. *
  283. * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
  284. */
  285. @Override
  286. public void onServiceConnected(ComponentName name, IBinder service) {
  287. mService = ((LocalBinder) service).getService();
  288. if (protocolClicked != null && protocolClicked.equals("PANIC")) {
  289. mService.startListeners();
  290. } else if (protocolClicked != null) {
  291. mService.toggleListener(protocolClicked);
  292. }
  293. protocolClicked = null;
  294. }
  295. /**
  296. * After the service is unbound, delete reference.
  297. *
  298. * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
  299. */
  300. @Override
  301. public void onServiceDisconnected(ComponentName name) {
  302. mService = null;
  303. }
  304. };
  305. /**
  306. * Checks if the phone ist rooted and if porthack is installed. Sets flags
  307. * {@link isRooted} and {@link porthackInstalled}
  308. */
  309. private void checkRootAndPorthack() {
  310. isRooted = false;
  311. porthackInstalled = false;
  312. Process p;
  313. try {
  314. String found = "Found";
  315. String notFound = "Not found";
  316. String command = "[ -f /data/local/p ] && echo " + found
  317. + " || echo " + notFound;
  318. p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
  319. BufferedReader in = new BufferedReader(new InputStreamReader(
  320. p.getInputStream()));
  321. /*
  322. * int av = byte[] b = new byte[av]; if (av != 0) { in.read(b); }
  323. */
  324. String echoResponse = in.readLine();
  325. Log.i("MainAc", echoResponse);
  326. if (echoResponse.equals(found)) {
  327. isRooted = true;
  328. porthackInstalled = true;
  329. } else if (echoResponse.equals(notFound)) {
  330. isRooted = true;
  331. }
  332. } catch (Exception e) {
  333. e.printStackTrace();
  334. }
  335. Log.i("MainAc", "Rooted: " + isRooted + " Porthack: "
  336. + porthackInstalled);
  337. }
  338. /**
  339. * Returns an intent to start HoneyService.
  340. *
  341. * @return An Intent to start HoneyService
  342. */
  343. private Intent getServiceIntent() {
  344. return new Intent(this, HoneyService.class);
  345. }
  346. /**
  347. * Checks if user selected paranoid mode.
  348. *
  349. * @return True when paranoid mode is selected, else returns false.
  350. */
  351. private boolean isParanoid() {
  352. return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
  353. }
  354. /**
  355. * Initializes the ListView. Creating its contents dynamic from protocol
  356. * res/values/protocols.xml
  357. */
  358. private void initListView() {
  359. ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
  360. for (String protocol : getResources().getStringArray(R.array.protocols)) {
  361. HashMap<String, String> d = new HashMap<String, String>();
  362. d.put("light", String.valueOf(R.drawable.light_grey));
  363. d.put("protocol", protocol);
  364. d.put("connections", "-");
  365. data.add(d);
  366. }
  367. listView = (ListView) findViewById(R.id.listViewProtocols);
  368. adapter = new ListViewAdapter(getLayoutInflater(), data);
  369. listView.setAdapter(adapter);
  370. listView.setOnTouchListener(new OnTouchListener() {
  371. @Override
  372. public boolean onTouch(View v, MotionEvent event) {
  373. return gestureDetector.onTouchEvent(event);
  374. }
  375. });
  376. listView.setOnItemClickListener(new OnItemClickListener() {
  377. @Override
  378. public void onItemClick(AdapterView<?> parent, View view,
  379. int position, long id) {
  380. String protocolName = (String) ((HashMap<?, ?>) adapter
  381. .getItem(position)).get("protocol");
  382. if (isServiceRunning()) {
  383. mService.toggleListener(protocolName);
  384. if (!mService.hasRunningListeners()) {
  385. stopAndUnbind();
  386. }
  387. } else {
  388. protocolClicked = protocolName;
  389. startAndBind();
  390. }
  391. }
  392. });
  393. }
  394. /**
  395. * Checks if a {@link HoneyService} instance is running.
  396. *
  397. * @return True if {@link HoneyService} is running, else false.
  398. */
  399. private boolean isServiceRunning() {
  400. ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
  401. for (RunningServiceInfo service : manager
  402. .getRunningServices(Integer.MAX_VALUE)) {
  403. if (service.service.getClassName().equals(
  404. HoneyService.class.getName())) {
  405. return true;
  406. }
  407. }
  408. return false;
  409. }
  410. /**
  411. * Deletes all session related Data.
  412. */
  413. private void deleteSessionData() {
  414. sessionEditor.clear();
  415. sessionEditor.commit();
  416. }
  417. /**
  418. * Register broadcast receiver for custom broadcast.
  419. *
  420. * @see #BROADCAST
  421. */
  422. private void registerReceiver() {
  423. LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
  424. new IntentFilter(BROADCAST));
  425. }
  426. /**
  427. * Unregisters broadcast receiver for custom broadcast.
  428. *
  429. * @see #BROADCAST
  430. */
  431. private void unregisterReceiver() {
  432. LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
  433. }
  434. /**
  435. * Receiver for custom broadcast.
  436. *
  437. * @see #BROADCAST
  438. */
  439. private BroadcastReceiver mReceiver = new BroadcastReceiver() {
  440. @Override
  441. public void onReceive(Context context, Intent intent) {
  442. // Update user interface.
  443. updateUI();
  444. }
  445. };
  446. /**
  447. * Register broadcast receiver for network state changes.
  448. *
  449. * @see ConnectivityManager#CONNECTIVITY_ACTION
  450. */
  451. private void registerNetReceiver() {
  452. IntentFilter intent = new IntentFilter();
  453. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
  454. registerReceiver(netReceiver, intent);
  455. }
  456. /**
  457. * Unregister broadcast receiver for network state changes.
  458. */
  459. private void unregisterNetReceiver() {
  460. unregisterReceiver(netReceiver);
  461. }
  462. /**
  463. * Receiver for network state change events.
  464. */
  465. private BroadcastReceiver netReceiver = new BroadcastReceiver() {
  466. @Override
  467. public void onReceive(Context context, Intent intent) {
  468. updateConnectionInfText();
  469. }
  470. };
  471. /**
  472. * Updates Information shown by the GUI.
  473. */
  474. private void updateUI() {
  475. boolean activeListeners = false;
  476. boolean activeHandlers = false;
  477. boolean yellowLight = false;
  478. // Check for all protocols if listeners are active and attacks have been
  479. // recorded
  480. // Update protocol lights and connection information.
  481. for (String protocol : getResources().getStringArray(R.array.protocols)) {
  482. // Check if protocol is active
  483. if (sessionPref.getBoolean(protocol + LISTENER, false)) {
  484. activeListeners = true;
  485. int handlerCount = sessionPref.getInt(protocol + HANDLER_COUNT,
  486. 0);
  487. // Check if attacks have been recorded in this session.
  488. if (handlerCount > 0) {
  489. activeHandlers = true;
  490. updateProtocolLight(LIGHT_RED, protocol);
  491. updateProtocolConnections(handlerCount, protocol);
  492. } else {
  493. // Check if the bssid of the wireless network has already
  494. // been recorded as infected.
  495. Logger.isBssidSeen(getApplicationContext(), protocol,
  496. HelperUtils.getBSSID(getApplicationContext()),
  497. logResultReceiver);
  498. if (isBssidSeen) {
  499. updateProtocolLight(LIGHT_YELLOW, protocol);
  500. yellowLight = true;
  501. } else {
  502. updateProtocolLight(LIGHT_GREEN, protocol);
  503. }
  504. updateProtocolConnections(0, protocol);
  505. }
  506. } else {
  507. updateProtocolLight(LIGHT_GREY, protocol);
  508. }
  509. }
  510. // Update the big attack indicator.
  511. if (activeListeners) {
  512. if (activeHandlers) {
  513. updateStatusLight(LIGHT_RED);
  514. } else {
  515. if (yellowLight) {
  516. updateStatusLight(LIGHT_YELLOW);
  517. } else {
  518. updateStatusLight(LIGHT_GREEN);
  519. }
  520. }
  521. ((ToggleButton) findViewById(R.id.toggleButtonOnOff))
  522. .setChecked(true);
  523. findViewById(R.id.checkBoxParanoid).setEnabled(false);
  524. } else {
  525. updateStatusLight(LIGHT_GREY);
  526. ((ToggleButton) findViewById(R.id.toggleButtonOnOff))
  527. .setChecked(false);
  528. findViewById(R.id.checkBoxParanoid).setEnabled(true);
  529. }
  530. }
  531. /**
  532. * Sets the big light indicator.
  533. *
  534. * @param light
  535. * Integer code to set the light color.
  536. * @see #LIGHT_GREY
  537. * @see #LIGHT_GREEN
  538. * @see #LIGHT_RED
  539. * @see #LIGHT_YELLOW
  540. */
  541. private void updateStatusLight(int light) {
  542. switch (light) {
  543. case LIGHT_GREY:
  544. ((ImageView) findViewById(R.id.imageViewLight))
  545. .setImageResource(R.drawable.light_grey_large);
  546. break;
  547. case LIGHT_GREEN:
  548. ((ImageView) findViewById(R.id.imageViewLight))
  549. .setImageResource(R.drawable.light_green_large);
  550. break;
  551. case LIGHT_RED:
  552. ((ImageView) findViewById(R.id.imageViewLight))
  553. .setImageResource(R.drawable.light_red_large);
  554. break;
  555. case LIGHT_YELLOW:
  556. ((ImageView) findViewById(R.id.imageViewLight))
  557. .setImageResource(R.drawable.light_yellow_large);
  558. break;
  559. }
  560. }
  561. /**
  562. * Sets the light indicator for a given protocol.
  563. *
  564. * @param light
  565. * Integer code to set the light color.
  566. * @param protocolName
  567. * Name of the protocol which should be updated.
  568. */
  569. private void updateProtocolLight(int light, String protocolName) {
  570. for (int i = 0; i < adapter.getCount(); ++i) {
  571. HashMap<String, String> d = (HashMap<String, String>) adapter
  572. .getItem(i);
  573. if (d.get("protocol").equals(protocolName)) {
  574. switch (light) {
  575. case LIGHT_GREY:
  576. d.put("light", String.valueOf(R.drawable.light_grey));
  577. d.put("connections", "-");
  578. break;
  579. case LIGHT_GREEN:
  580. d.put("light", String.valueOf(R.drawable.light_green));
  581. break;
  582. case LIGHT_RED:
  583. d.put("light", String.valueOf(R.drawable.light_red));
  584. break;
  585. case LIGHT_YELLOW:
  586. d.put("light", String.valueOf(R.drawable.light_yellow));
  587. break;
  588. }
  589. }
  590. }
  591. adapter.notifyDataSetChanged();
  592. }
  593. /**
  594. * Sets the connections count for a given protocol.
  595. *
  596. * @param connections
  597. * New value for recorded connections.
  598. * @param protocolName
  599. * Name of the protocol which should be updated.
  600. */
  601. private void updateProtocolConnections(int connections, String protocolName) {
  602. for (int i = 0; i < adapter.getCount(); ++i) {
  603. HashMap<String, String> d = ((HashMap<String, String>) adapter
  604. .getItem(i));
  605. if (d.get("protocol").equals(protocolName)) {
  606. d.put("connections", String.valueOf(connections));
  607. }
  608. }
  609. adapter.notifyDataSetChanged();
  610. }
  611. /**
  612. * Gets Information about connection state and updates the GUI.
  613. */
  614. private void updateConnectionInfText() {
  615. TextView ssidView = (TextView) findViewById(R.id.textViewSSIDValue);
  616. TextView bssidView = (TextView) findViewById(R.id.textViewBSSIDValue);
  617. TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
  618. TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
  619. externalIPView.setText("Loading...");
  620. // Update the connection information
  621. updateConnectionInfo();
  622. SetExternalIPTask async = new SetExternalIPTask();
  623. async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
  624. // Get connection information
  625. String ssid = sessionPref.getString(SSID, null);
  626. String bssid = sessionPref.getString(BSSID, null);
  627. String internalIP = sessionPref.getString(INTERNAL_IP, null);
  628. // Set text fields
  629. if (ssid != null)
  630. ssidView.setText(ssid);
  631. else
  632. ssidView.setText("-");
  633. if (bssid != null)
  634. bssidView.setText(bssid);
  635. else
  636. bssidView.setText("-");
  637. if (internalIP != null)
  638. internalIPView.setText(internalIP);
  639. else
  640. internalIPView.setText("-");
  641. }
  642. /**
  643. * Updates the connection info and saves them in the the SharedPreferences
  644. * for session data.
  645. *
  646. * @param context
  647. * Needs a context to get system recourses.
  648. * @see MainActivity#SESSION_DATA
  649. */
  650. private void updateConnectionInfo() {
  651. SharedPreferences pref = context.getSharedPreferences(
  652. MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
  653. Editor editor = pref.edit();
  654. editor.putString(MainActivity.SSID, HelperUtils.getSSID(context));
  655. editor.putString(MainActivity.BSSID, HelperUtils.getBSSID(context));
  656. editor.putString(MainActivity.INTERNAL_IP,
  657. HelperUtils.getInternalIP(context));
  658. editor.commit();
  659. }
  660. /**
  661. * Task to find out the external IP.
  662. *
  663. * @author Lars Pandikow
  664. */
  665. private class SetExternalIPTask extends AsyncTask<String, Void, String> {
  666. @Override
  667. protected String doInBackground(String... url) {
  668. String ipAddress = null;
  669. try {
  670. HttpClient httpclient = new DefaultHttpClient();
  671. HttpGet httpget = new HttpGet(url[0]);
  672. HttpResponse response;
  673. response = httpclient.execute(httpget);
  674. HttpEntity entity = response.getEntity();
  675. entity.getContentLength();
  676. String str = EntityUtils.toString(entity);
  677. JSONObject json_data = new JSONObject(str);
  678. ipAddress = json_data.getString("ip");
  679. } catch (Exception e) {
  680. e.printStackTrace();
  681. }
  682. return ipAddress;
  683. }
  684. @Override
  685. protected void onPostExecute(String result) {
  686. sessionEditor.putString(MainActivity.EXTERNAL_IP, result);
  687. sessionEditor.commit();
  688. TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
  689. if (result != null)
  690. externalIPView.setText(result);
  691. else
  692. externalIPView.setText("-");
  693. }
  694. };
  695. /* ############# Help functions for animation ################## */
  696. @Override
  697. public boolean onTouchEvent(MotionEvent event) {
  698. return gestureDetector.onTouchEvent(event);
  699. }
  700. /**
  701. * Initializes variables for screen animation
  702. */
  703. private void initViewAnimator() {
  704. viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
  705. gestureDetector = new GestureDetector(this, simpleOnGestureListener);
  706. animFlipInLR = AnimationUtils.loadAnimation(this,
  707. R.anim.in_left_to_right);
  708. animFlipOutLR = AnimationUtils.loadAnimation(this,
  709. R.anim.out_left_to_right);
  710. animFlipInRL = AnimationUtils.loadAnimation(this,
  711. R.anim.in_right_to_left);
  712. animFlipOutRL = AnimationUtils.loadAnimation(this,
  713. R.anim.out_right_to_left);
  714. }
  715. /**
  716. * Called when a swipe to the Left is registered.
  717. */
  718. private void swipeRightToLeft() {
  719. if (viewAnimator.getDisplayedChild() == 0) {
  720. viewAnimator.setInAnimation(animFlipInRL);
  721. viewAnimator.setOutAnimation(animFlipOutRL);
  722. viewAnimator.setDisplayedChild(1);
  723. }
  724. }
  725. /**
  726. * Called when a swipe to the Right is registered.
  727. */
  728. private void swipeLeftToRight() {
  729. if (viewAnimator.getDisplayedChild() == 1) {
  730. viewAnimator.setInAnimation(animFlipInLR);
  731. viewAnimator.setOutAnimation(animFlipOutLR);
  732. viewAnimator.setDisplayedChild(0);
  733. }
  734. }
  735. SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
  736. @Override
  737. public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
  738. float velocityY) {
  739. float sensitvity = 50;
  740. if ((e1.getX() - e2.getX()) > sensitvity) {
  741. swipeRightToLeft();
  742. } else if ((e2.getX() - e1.getX()) > sensitvity) {
  743. swipeLeftToRight();
  744. }
  745. return true;
  746. }
  747. };
  748. }