MainActivity.java 23 KB

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