Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

>>> Create project - - - Select File New - New Project... Choose Empty Activity template, and click Next. On New Project window, fill


imageimageimageimageimageimageimage

>>> Create project - - - Select "File" "New" - "New Project..." Choose "Empty Activity" template, and click "Next". On "New Project" window, fill out information. Click "Finish". o Project name: AsyncTask o Package name: edu.csustan.cs3810.asynctask Save location: \codes\AsyncTask >>> Resources - - Define constants in resource files. Create dimens.xml, and add a constant, "layout_space". 20dp - In themes.xml, add a text size, "textSize" as shown in rectangle. 24sp >>> Main (View): UI Design In this step, we add UI components and arrange them on the screen. Go to "activity_main.xml". (Design). Change layout to "Relative Layout". For "Relative Layout", set "padding" attribute with "layout_space" constant. padding padding [@dimen/layout_space, ?, ?, ?, ?] @dimen/layout_space Add an input field and a button. Set IDs and Texts, and some attributes ID: inputTime Text: (none) InputType: number Hint: Enter time in seconds Component Tree RelativeLayout inputTime(Number) btnRun- "RUN" + Ab IblMsg ID: btnRun Text: RUN ID: IblMsg Text: (none) btn Run and inputTime has 20dp gap. layout_margin layout_margin layout_marginStart layout_marginLeft [?, ?, 20dp, ?, ?] layout_marginTop 20dp Locate "IblMsg" TextView. o IblMsg is aligned to the left of the btnRun. layout_alignLeft @id/btnRun layout_alignParen layout alignParen o IblMsg is below btnRun. layout_below layout_centerHori layout_centerinPal @id/inputTime @id/btnRun @id/btnRun @id/inputTime @id/btnRun o IblMsg and btn Run has 20dp gap. layout_margin [?, ?, 20dp, ?, ?] - Locate "btnRun" button. layout_margin layout_marginStart o btnRun is aligned to the left of the inputTime. layout_alignLeft @id/inputTime layout_alignParen @id/inputTime 10 layout_marginLeft layout_marginTop 20dp Expected result is as follows. layout_alignParen@id/lblMsg btnRun is below inputTime. layout_below @id/inputTime layout_centerHori @id/inputTime layout_centerInPa @id/lblMsg Enter time in seconds 20 RUN >>> AsyncTask (Model) In this step, we create a class (inheriting AsyncTask) that runs in background, receives input from main activity, and returns result to the main activity. Create "Task.java". Right-click on package edu.csustan.cs3810.asynctask". Select "New" "Java Class". Fill out class name and hit Enter key. " Name: Task We see "error" (underlined in red color) on the class definition. We need to implement required methods for the AsyncTask class. Add "doInBackground()" method. Click "Task", and hit alt + enter key. Click "Implement methods. public class Task extends AsyncTask { Implement methods } Make 'Task' abstract C Task C Class Interface Enum @Annotation We create "Task" class. app manifests java New Java Class edu.csustan.cs3810.asynctask MainActivity C Task ivity_main.xml x Task.java X MainActivity.java package edu.csustan.cs3810.asynctask; public class Task { "Task" inherits "AsyncTask" class to run in the background. Add codes shown in rectangle. 5: integer "Finished": String public class Task extends AsyncTask { } o "dolnBackground()" is chosen. Click "OK". 12 Select Methods to Implement ==> android.os.AsyncTask (m) dolnBackground(params:Params...): Result Skeleton "dolnBackground()" is created. public class Task extends AsyncTask { @Override protected String doInBackground (Integer... integers) { return null; o Add codes as shown in rectangle. Change the name of parameters to params. @Override protected String doInBackground (Integer... params) { } int runningTime =params[0] 1000; // in seconds SystemClock.sleep(running Time); return "Finished"; // result "params[0]" is the time value retrieved from the input field. "runningTime" is time in seconds. "SystemClock.sleep( ) sleeps for the given time. The method returns result, "Finished". - Add "onPostExecute()" method. @Override protected void onPostExecute(String result) { } lblMsg.setText(result); "result" is the result that "dolnBackground()" method returns. "onPostExecute()" method is called after "dolnBackground()" finishes. It shows the result to "lblMsg" Ul component. Please ignore the error of IblMsg. The error on "IblMsg" will be gone when we define the IbIMsg at the next step. [Variable] Define an instance variable as shown in rectangle. public class Task extends AsyncTask { private TextView lblMsg; o "lblMsg" is the UI component (in main activity) to which result is returned. [ Constructor] Add a constructor as shown in rectangle. public class Task extends AsyncTask { private TextView lblMsg; public Task(TextView lblMsg) { this.lblMsg = lblMsg; >>> Main (Controller): Logic Code In this step, we will make codes that run methods in Task object (in the background). Open "MainActivity.java". [Variable] Add a TextView instance variable as shown in rectangle. public class MainActivity extends AppCompatActivity private TextView lblMsg; [Method: onCreate()] In onCreate(), add codes (shown in rectangle) to access IblMsg UI component. @Override protected void onCreate(Bundle savedInstanceState) { } super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); |blMsg = findViewById(R.id.lblMsg); [Method: run()] Add a method (that is called by click event of "RUN" button) to call methods in Task object. public void run(View v) { // make result empty lblMsg.setText(""); // get time EditText inputTime = findViewById(R.id.inputTime); int time = Integer.parseInt(inputTime.getText().toString()); // run task in background Task task = new Task(lblMsg); task.execute(time); time Main activity 5 RUN IblMsg AsyncTask >>> Test task.execute(time) "Finished" setText("") Run application. "Main" screen (activity) is shown. 7:25 AM AsyncTask Enter time in seconds RUN We make "IblMsg" empty. We get time from input field, and run methods (In task object) in the background (with input value, time). Type 5, and click "RUN" button. After 5 seconds, we see "Finished". The "sleep(5 seconds)" is running in the background. The value of result ("Finished") is returned and shown to lblMsg. Connect the button UI component to event handler. Go back to "activity_main.xml", and choose "btnRun" on Component Tree. Component Tree RelativeLayout Ab inputTime (Number) btnRun "RUN" Ab IblMsg Choose "run" method for onClick event. 7:26 " AsyncTask 5 RUN Finished onClick overScrollMode > padding run MainActivity run he >>> Update AsyncTask: show progress In this step, we will change Task class to show progress of background thread. We want to print the remaining time before printing "Finished". Main activity AsyncTask 5 onProgressUpdate() dolnBackground() 5 RUN 5,4,3, 2,1 5, 4, 3, 2, 1 publishProgress( ) every second result ("Finished") "Finished" IblMsg Notify end of process onPostExecute() "onProgressUpdate()" method is called when background thread ("doln Background()") runs "publishProgress()" method. In our case, "doln Background()" method runs "publishProgress()" with remaining time every second. "onProgressUpdate()" sends the remaining time to main Activity which shows the remaining time to lblMsg UI component. The type of " in publishProgress() method should be same as the type of the progress (second parameter of AsyncTask). In our case, the type is "Integer". - Change the type of progress in Task class definition as shown in rectangle. progress: remaining time (5, 4, 3, 2, or 1) public class Task extends AsyncTask { private TextView lblMsg; Create "onProgressUpdate()" method. @Override protected void onProgressUpdate (Integer... progress) { int remainingTime = progress[0]; lblMsg.setText(String.valueOf(remaining Time)); o "progress[0]" is the remaining time that "dolnBackground()" method returns. The remaining time is shown to IblMsg UI component. Change codes (as shown in rectangle) of "doInBackground()" method. @Override protected String doInBackground (Integer... params) { int runningTime = params[0]; // in seconds for (int i=runningTime; i > 0; i--) { } } publishProgress (i); SystemClock.sleep( ms: 1000); return "Finished"; // result For example, runningTime is 5. In the "for" loop, it calls publish Progress() with 5, 4, 3, 2, and 1 every second. "i" variable means the remaining time. o "publishProgress()" is the built-in method. We don't have to implement the method. o System Clock.sleep(1000) waits for one second. >>> Test Run application. Type 5, and click "RUN" button. The remaining time is shown from 5 to 1 (which is the progress status), and last, "Finished" is printed. 7:38 A AsyncTask 5 3 RUN 7:38 A AsyncTask 5 RUN Finished

Step by Step Solution

There are 3 Steps involved in it

Step: 1

Based on the provided instructions heres how you can set up you... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Intermediate Accounting

Authors: J. David Spiceland, James Sepe, Mark Nelson, Wayne Thomas

10th edition

1260481956, 1260310175, 978-1260481952

More Books

Students also viewed these Programming questions