Advertisement
praymes

AsyncSvetofar

May 15th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.22 KB | None | 0 0
  1. package com.example.eurynomus.trafficlightmine;
  2.  
  3. import android.graphics.Color;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.TextView;
  9.  
  10. import com.example.eurynomus.trafficlightmine.R;
  11.  
  12. public class MainActivity extends AppCompatActivity
  13. {
  14. // Define constant Logic
  15. //----------------------------------------------------------------------------------------------
  16. // С goToRed и goToGreen оказват посоката на движение на светлината на светофара.
  17. private final int goToRed = 0;
  18. private final int goToGreen = 2;
  19. // Използваме redLight, yellowLight, greenLight, за да поясним в кода(най-вече в switch-овете)
  20. // в какво състояние е светофара и какво се случваа, докато е в това състояние.
  21. private final int redLight = 0;
  22. private final int yellowLight = 1;
  23. private final int greenLight = 2;
  24.  
  25. // Layout Resources
  26. //----------------------------------------------------------------------------------------------
  27. // Създаваме променливи, с които ще манипулираме ресурсите във View-то.
  28. private TextView redLightTextView;
  29. private TextView yellowLightTextView;
  30. private TextView greenLightTextView;
  31. private Button startBtn;
  32. private Button resetBtn;
  33. private Button stopBtn;
  34.  
  35. // logic Variables
  36. //----------------------------------------------------------------------------------------------
  37. // Използваме isWorking САМО когато пускаме нишката в началото със Start бутона, понеже след
  38. // натискане на STOP нишката не спира, а по-скоро е в режим Pause и при повторно натискане на
  39. // START ние не трябва да пускаме нова нишка, а просто да продължим настоящата(Resume work)
  40. private boolean isWorking;
  41. // Използва се в случай, че RESET бутона е натиснат. Когато isReset стане true ще се изпълни
  42. // логиката, която сме написали и след това ще се върне в състояние false
  43. private boolean isReset;
  44. // Използва се, когато натискаме STOP бутона. Служи като тригер, чрез който светофара се спира
  45. // (PAUSE) и започва да се изпълнява новата логика. При натискането на START или RESET бутона,
  46. // светофара продължава работата си (RESUME WORK) както следва по логиката на натиснатият бутон.
  47. private boolean isStopped;
  48. // В nCurrentLight се пази настоящата светлина,
  49. // работеща на светофара(redLight, yellowLifht, greenLight)
  50. private int nCurrentLight;
  51. // В nLightPath се пази пътя на светлината на светофата (дали е goToRed или goToGreen)
  52. private int nLightPath;
  53.  
  54.  
  55. // Overrides
  56. //----------------------------------------------------------------------------------------------
  57.  
  58. @Override
  59. protected void onCreate(Bundle savedInstanceState)
  60. {
  61. super.onCreate(savedInstanceState);
  62. setContentView(R.layout.activity_main);
  63.  
  64. setLayoutResources();
  65. initializeLogicVariables();
  66.  
  67. // В началото светофарът е спрян, затова всичките му светлини трябва да са Сиви/Черни/etc.
  68. setTrafficLightsColor(Color.GRAY, Color.GRAY, Color.GRAY);
  69.  
  70. startBtn.setOnClickListener(new View.OnClickListener()
  71. {
  72. @Override
  73. public void onClick(View v)
  74. {
  75. // Понеже в началото светофарът е изключен, ще влезем в този IF statement.
  76. // Вътре ще го включим и повече няма да влезем в този IF statement.
  77. if(!isWorking)
  78. {
  79. // Задаваме стойност true, което означава, че светофарът работи.
  80. isWorking = true;
  81. // Извикваме метода, който включва светофара.
  82. startTrafficLight();
  83. }
  84.  
  85. // След като натиснем един бутон, другите се връщат в началното си състояние(RESET),
  86. // а натиснатият бутон се изключва, за да не бъде натиснат повторно.
  87. isReset = false;
  88. isStopped = false;
  89. startBtn.setEnabled(false);
  90. resetBtn.setEnabled(true);
  91. stopBtn.setEnabled(true);
  92. }
  93. });
  94.  
  95. resetBtn.setOnClickListener(new View.OnClickListener()
  96. {
  97. @Override
  98. public void onClick(View v)
  99. {
  100. // След като натиснем един бутон, другите се връщат в началното си състояние(RESET),
  101. // а натиснатият бутон се изключва, за да не бъде натиснат повторно.
  102. isStopped = false;
  103. isReset = true;
  104. startBtn.setEnabled(true);
  105. resetBtn.setEnabled(false);
  106. stopBtn.setEnabled(true);
  107. }
  108. });
  109.  
  110. stopBtn.setOnClickListener(new View.OnClickListener()
  111. {
  112. @Override
  113. public void onClick(View v)
  114. {
  115. // След като натиснем един бутон, другите се връщат в началното си състояние(RESET),
  116. // а натиснатият бутон се изключва, за да не бъде натиснат повторно.
  117. isStopped = true;
  118. isReset = false;
  119. stopBtn.setEnabled(false);
  120. startBtn.setEnabled(true);
  121. resetBtn.setEnabled(true);
  122. // Когато светофарът спре, тогава свети само Жълто(по-условие).
  123. nCurrentLight = yellowLight;
  124. }
  125. });
  126.  
  127. }
  128.  
  129.  
  130. // Methods
  131. //----------------------------------------------------------------------------------------------
  132. // Този метод създава НИШКА, която включва светофара и я стартира.
  133. //
  134. private void startTrafficLight()
  135. {
  136. // Създаваме нишката
  137. Thread trafficLightThread = new Thread(new Runnable()
  138. {
  139. // В RUN описваме логиката, която нишката ще изпълнява.
  140. @Override
  141. public void run()
  142. {
  143. // Докато светофарът работи, нишката няма да спре работа.
  144. // (В случеят имаме безкраен цикъл и нишката няма да завърши).
  145. while(isWorking)
  146. {
  147. trafficLightSwitch();
  148. }
  149. }
  150. });
  151.  
  152. // Стартираме нишката
  153. trafficLightThread.start();
  154. }
  155.  
  156. // Този Метод проверява коя светлина на светофара работи на момента и изпълнява логиката
  157. // свързана с нея(смяна на цветовете на светофара, задържане в същото състояние за определен
  158. // интервал от време, смяна на светлината, смяна на посоката на светлината, etc.).
  159. private void trafficLightSwitch()
  160. {
  161. switch (nCurrentLight)
  162. {
  163. case redLight:
  164. nLightPath = greenLight;
  165. trafficLightColorSwitch();
  166. nCurrentLight = yellowLight;
  167. sameLightLooper(5);
  168. break;
  169. case yellowLight:
  170. trafficLightColorSwitch();
  171. if(nLightPath == goToGreen)
  172. nCurrentLight = greenLight;
  173. else if(nLightPath == goToRed)
  174. nCurrentLight = redLight;
  175. sameLightLooper(3);
  176. break;
  177. case greenLight:
  178. nLightPath = redLight;
  179. trafficLightColorSwitch();
  180. nCurrentLight = yellowLight;
  181. sameLightLooper(5);
  182. break;
  183. }
  184. }
  185.  
  186. // Този метод променя цветовете на светофара в зависимост от състоянието на работещата
  187. // в момента светлина.
  188. private void trafficLightColorSwitch()
  189. {
  190. switch (nCurrentLight)
  191. {
  192. case redLight:
  193. setTrafficLightsColor(Color.RED, Color.GRAY, Color.GRAY);
  194. break;
  195. case yellowLight:
  196. setTrafficLightsColor(Color.GRAY, Color.YELLOW, Color.GRAY);
  197. break;
  198. case greenLight:
  199. setTrafficLightsColor(Color.GRAY, Color.GRAY, Color.GREEN);
  200. break;
  201. }
  202. }
  203.  
  204. // Този метод отговаря за циклите и времето, което светофарът ще стои в дадена позиция.
  205. private void sameLightLooper(int maxLoopTime)
  206. {
  207. // nLoopTimePassed оказва колко време е минало от началото на светлината.
  208. int nLoopTimePassed = 0;
  209. // nMaxLoopTime оказва колко време светлината трябва да стои в дадено състояние.
  210. int nMaxLoopTime = maxLoopTime * 100;
  211. // Това не знам защо го имам ама май ми трябваше, за да не се чупи много =D
  212. boolean toReturn = false;
  213.  
  214. // Blink се използва за минагето на жълтият светофар, докато е в режим STOP
  215. int blink = 0;
  216. // Цикълът, който се изпълнява докато сме в режим STOP(т.е. натиснали сме STOP бутона).
  217. while(isStopped && !isReset)
  218. {
  219. if(!toReturn)
  220. toReturn = !toReturn;
  221.  
  222. nLoopTimePassed++;
  223. if (nLoopTimePassed % 50 == 0)
  224. {
  225. nLoopTimePassed = 0;
  226. if (blink == 0)
  227. {
  228. blink = 1;
  229. setTrafficLightsColor(Color.GRAY, Color.GRAY, Color.GRAY);
  230. } else if (blink == 1)
  231. {
  232. blink = 0;
  233. setTrafficLightsColor(Color.GRAY, Color.YELLOW, Color.GRAY);
  234. }
  235. }
  236. try
  237. {
  238. Thread.sleep(10);
  239. } catch (InterruptedException e)
  240. {
  241. e.printStackTrace();
  242. }
  243. }
  244.  
  245. // Цикълът, който се изпълнява когато влезем в режим RESET(т.е. натиснали сме RESET бутона).
  246. if(isReset)
  247. {
  248. isReset = false;
  249. nCurrentLight = yellowLight;
  250. nLightPath = greenLight;
  251. runOnUiThread(new Runnable()
  252. {
  253. @Override
  254. public void run() {
  255. resetBtn.setEnabled(false);
  256. }
  257. });
  258.  
  259. return;
  260. }
  261.  
  262. if(toReturn)
  263. return;
  264.  
  265. // Цикълът, който се изпълнява когато влезем в режим START или след RESET или когато
  266. // пуснем светофара за пръв път(т.е. натиснали сме START бутона или т.н.)
  267. // P.S. - Това е обикновената(нормалната) работа да светофара.
  268. while((nLoopTimePassed < nMaxLoopTime) && !isStopped && !isReset)
  269. {
  270. if(!toReturn)
  271. toReturn = !toReturn;
  272.  
  273. nLoopTimePassed++;
  274. try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
  275. }
  276. }
  277.  
  278. // Метод, който присвоява на ресурсните променливи ресурсите КОИТО взимаме от View-то
  279. // и с които ще работим в последствие
  280. private void setLayoutResources()
  281. {
  282. redLightTextView = (TextView) findViewById(R.id.redLightTextView);
  283. yellowLightTextView = (TextView) findViewById(R.id.yellowLightTextView);
  284. greenLightTextView = (TextView) findViewById(R.id.greenLightTextView);
  285.  
  286. startBtn = (Button) findViewById(R.id.startBtn);
  287. resetBtn = (Button) findViewById(R.id.resetBtn);
  288. stopBtn = (Button) findViewById(R.id.stopBtn);
  289. }
  290.  
  291. // Метод за Инициализиране на променливите с начални стойности
  292. private void initializeLogicVariables()
  293. {
  294. isWorking = false;
  295. isReset = false;
  296. isStopped = false;
  297. nCurrentLight = redLight;
  298. nLightPath = goToGreen;
  299. }
  300.  
  301. // С този Метод Задаваме цветовете на Трите слетлини на светофара.
  302. // Използваме го при смяната на светлините.
  303. private void setTrafficLightsColor(int nRedLightColor, int nYellowLightColor, int nGreenLightColor)
  304. {
  305. redLightTextView.setBackgroundColor(nRedLightColor);
  306. yellowLightTextView.setBackgroundColor(nYellowLightColor);
  307. greenLightTextView.setBackgroundColor(nGreenLightColor);
  308. }
  309.  
  310. }
  311.  
  312.  
  313.  
  314.  
  315.  
  316.  
  317.  
  318. <?xml version="1.0" encoding="utf-8"?>
  319. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  320. xmlns:app="http://schemas.android.com/apk/res-auto"
  321. xmlns:tools="http://schemas.android.com/tools"
  322. android:layout_width="match_parent"
  323. android:layout_height="match_parent"
  324. tools:context=".MainActivity">
  325.  
  326. <TextView
  327. android:id="@+id/redLightTextView"
  328. android:layout_width="100dp"
  329. android:layout_height="100dp"
  330. android:layout_marginStart="8dp"
  331. android:layout_marginLeft="8dp"
  332. android:layout_marginTop="8dp"
  333. android:layout_marginEnd="8dp"
  334. android:layout_marginRight="8dp"
  335. android:layout_marginBottom="8dp"
  336. android:background="#333333"
  337. android:textSize="26sp"
  338. app:layout_constraintBottom_toBottomOf="parent"
  339. app:layout_constraintEnd_toEndOf="parent"
  340. app:layout_constraintStart_toStartOf="parent"
  341. app:layout_constraintTop_toTopOf="parent"
  342. app:layout_constraintVertical_bias="0.16000003" />
  343.  
  344. <TextView
  345. android:id="@+id/yellowLightTextView"
  346. android:layout_width="100dp"
  347. android:layout_height="100dp"
  348. android:layout_marginStart="8dp"
  349. android:layout_marginLeft="8dp"
  350. android:layout_marginTop="8dp"
  351. android:layout_marginEnd="8dp"
  352. android:layout_marginRight="8dp"
  353. android:layout_marginBottom="8dp"
  354. android:background="#333333"
  355. app:layout_constraintBottom_toBottomOf="parent"
  356. app:layout_constraintEnd_toEndOf="parent"
  357. app:layout_constraintStart_toStartOf="parent"
  358. app:layout_constraintTop_toBottomOf="@+id/redLightTextView"
  359. app:layout_constraintVertical_bias="0.0" />
  360.  
  361. <TextView
  362. android:id="@+id/greenLightTextView"
  363. android:layout_width="100dp"
  364. android:layout_height="100dp"
  365. android:layout_marginStart="8dp"
  366. android:layout_marginLeft="8dp"
  367. android:layout_marginTop="8dp"
  368. android:layout_marginEnd="8dp"
  369. android:layout_marginRight="8dp"
  370. android:layout_marginBottom="8dp"
  371. android:background="#333333"
  372. app:layout_constraintBottom_toBottomOf="parent"
  373. app:layout_constraintEnd_toEndOf="parent"
  374. app:layout_constraintStart_toStartOf="parent"
  375. app:layout_constraintTop_toBottomOf="@+id/yellowLightTextView"
  376. app:layout_constraintVertical_bias="0.0" />
  377.  
  378. <Button
  379. android:id="@+id/startBtn"
  380. android:layout_width="wrap_content"
  381. android:layout_height="wrap_content"
  382. android:layout_marginStart="8dp"
  383. android:layout_marginLeft="8dp"
  384. android:layout_marginTop="8dp"
  385. android:layout_marginEnd="8dp"
  386. android:layout_marginRight="8dp"
  387. android:layout_marginBottom="8dp"
  388. android:text="Start"
  389. app:layout_constraintBottom_toBottomOf="parent"
  390. app:layout_constraintEnd_toEndOf="parent"
  391. app:layout_constraintHorizontal_bias="0.07"
  392. app:layout_constraintStart_toStartOf="parent"
  393. app:layout_constraintTop_toBottomOf="@+id/greenLightTextView"
  394. app:layout_constraintVertical_bias="0.31" />
  395.  
  396. <Button
  397. android:id="@+id/resetBtn"
  398. android:layout_width="wrap_content"
  399. android:layout_height="wrap_content"
  400. android:layout_marginStart="8dp"
  401. android:layout_marginLeft="8dp"
  402. android:layout_marginTop="8dp"
  403. android:layout_marginEnd="8dp"
  404. android:layout_marginRight="8dp"
  405. android:layout_marginBottom="8dp"
  406. android:text="Reset"
  407. app:layout_constraintBottom_toBottomOf="parent"
  408. app:layout_constraintEnd_toEndOf="parent"
  409. app:layout_constraintHorizontal_bias="0.16"
  410. app:layout_constraintStart_toEndOf="@+id/startBtn"
  411. app:layout_constraintTop_toBottomOf="@+id/greenLightTextView"
  412. app:layout_constraintVertical_bias="0.311" />
  413.  
  414. <Button
  415. android:id="@+id/stopBtn"
  416. android:layout_width="wrap_content"
  417. android:layout_height="wrap_content"
  418. android:layout_marginStart="8dp"
  419. android:layout_marginLeft="8dp"
  420. android:layout_marginTop="8dp"
  421. android:layout_marginEnd="8dp"
  422. android:layout_marginRight="8dp"
  423. android:layout_marginBottom="8dp"
  424. android:text="Stop"
  425. app:layout_constraintBottom_toBottomOf="parent"
  426. app:layout_constraintEnd_toEndOf="parent"
  427. app:layout_constraintHorizontal_bias="0.46"
  428. app:layout_constraintStart_toEndOf="@+id/resetBtn"
  429. app:layout_constraintTop_toBottomOf="@+id/greenLightTextView"
  430. app:layout_constraintVertical_bias="0.311" />
  431. </android.support.constraint.ConstraintLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement