MainActivity.java 23 KB

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