MainActivity.java 21 KB

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