Software Practice 3 Today s lecture Today s Task

Similar documents
Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5

Android Fundamentals - Part 1

MOBILE APPLICATION DEVELOPMENT LECTURE 10 SERVICES IMRAN IHSAN ASSISTANT PROFESSOR

Services are software components designed specifically to perform long background operations.

Services. Background operating component without a visual interface Running in the background indefinitely

CS378 -Mobile Computing. Services and Broadcast Receivers

EMBEDDED SYSTEMS PROGRAMMING Android Services

ANDROID SERVICES, BROADCAST RECEIVER, APPLICATION RESOURCES AND PROCESS

Android. Broadcasts Services Notifications

Services. Marco Ronchetti Università degli Studi di Trento

CS371m - Mobile Computing. Responsiveness

Services. service: A background task used by an app.

Programming with Android: Notifications, Threads, Services. Luca Bedogni. Dipartimento di Scienze dell Informazione Università di Bologna

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Thread. A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables.

INTRODUCTION TO ANDROID

Application Fundamentals

Lecture 2 Android SDK

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

Minds-on: Android. Session 2

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Services & Interprocess Communication (IPC) CS 282 Principles of Operating Systems II Systems Programming for Android

Android Services & Local IPC: The Command Processor Pattern (Part 1)

Android Services & Local IPC: Overview of Programming Bound Services

Mobile and Ubiquitous Computing: Android Programming (part 4)

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

Android System Development Day-4. Team Emertxe

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu

Efficient Android Threading

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CS 351 Design of Large Programs Threads and Concurrency

7. MULTITHREDED PROGRAMMING

1. GOALS and MOTIVATION

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL II)

Services. Marco Ronchetti Università degli Studi di Trento

States of Activities. Active Pause Stop Inactive

CS11 Java. Fall Lecture 7

Threads Chate Patanothai

Multiple Activities. Many apps have multiple activities

Software Practice 3 Today s lecture Today s Task

Mobile Application Development Android

Java Threads. COMP 585 Noteset #2 1

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Notifications and Services. Landon Cox March 28, 2017

Software Practice 3 Today s lecture Today s Task Porting Android App. in real device

CHAPTER 15 ASYNCHRONOUS TASKS

Mobile Application Development Android

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Understanding Application

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Object Oriented Programming. Week 10 Part 1 Threads

Activities and Fragments

Activities. Repo:

Software Practice 1 - Multithreading

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Java s Implementation of Concurrency, and how to use it in our applications.

32. And this is an example on how to retrieve the messages received through NFC.

Java FX. Threads, Workers and Tasks

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

Android Services. Victor Matos Cleveland State University. Services

Inheritance Abstraction Polymorphism

Hydrogen Car Mobile Display

Mobile Development Lecture 9: Android & RESTFUL Services

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

An Overview of the Android Programming

Java Threads. Introduction to Java Threads

Termite WiFi Direct API

COMP4521 EMBEDDED SYSTEMS SOFTWARE

Programming Exercise 14: Inheritance and Polymorphism

Broadcast receivers. Marco Ronchetti Università degli Studi di Trento

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Mobile Computing. Introduction to Android

Midterm assessment - MAKEUP Fall 2010

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

Android Architecture and Binder. Dhinakaran Pandiyan Saketh Paranjape

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Communicating with a Server

Introduction to Mobile Application Development Using Android Week Four Video Lectures

Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Android Application Development

CMSC 132: Object-Oriented Programming II. Threads in Java

Mobile Application Development Android

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CS360 Lecture 12 Multithreading

REMOTE ACCESS TO ANDROID DEVICES. A Project. Presented to the faculty of the Department of Computer Science. California State University, Sacramento

User Interface Design & Development

Implementing a Download Background Service

UNDERSTANDING ACTIVITIES

The Java FutureTask. Douglas C. Schmidt

6.033 Spring 2018 Lecture #3

CSCD 330 Network Programming

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Transcription:

1 Software Practice 3 Today s lecture Today s Task Prof. Hwansoo Han T.A. Jeonghwan Park 43

2 MULTITHREAD IN ANDROID

3 Activity and Service before midterm after midterm

4 Java Thread Thread is an execution stream of a process Sharing a core between multiple threads Most of modern OS support multithread Android support multithread with some reasons Each thread is dedicated for its own job Separate foreground(ui) and background(other) thread

5 Multithread in Android Android manages UI with Main Thread and others with threads in Poll Threads The job for other threads is called as external Service The job for main thread which is not UI related work is called as local Service

6 Main Thread UI jobs are executed by special module for thread management, Looper Looper manages not only UI related jobs, but also all foreground jobs

ASYNCTASK 7

8 AsyncTask a class that supports main thread work and background thread work at the same time Executed AsyncTask is an object Cannot be reused executed only once Does not be cancelled when an activity is quitted Should be manually cancelled when an activity finished Only one AyncTask can be run at a time

AsyncTask Workflow 9

10 Callback Methods of AsyncTask onpreexecute() invoked on the main thread before the task is executed doinbackground(params...) invoked on the background thread immediately after onpreexecute() finishes executing This step is used to perform background computation that can take a long time The result of computation must be returned by this step and will be passed back to the last step

11 Callback Methods of AsyncTask onprogressupdate(progress...) invoked on the main thread after a call to publishprogress(progress) The timing of the execution is undefined This method is used to display any form of progress in the UI while the background computation is still executing onpostexecute(result) invoked on the main thread after the background computation finishes

12 Methods of AsyncTask execute(params...) Executes the task with the specified parameters cancel(boolean) Attempts to cancel execution of this task getstatus() Returns the current status of this task iscancelled() Returns true if this task was cancelled before it completed normally, else false

13 Special Method of AsyncTask publishprogress(progress...) Trigger the execution of onprogressupdate(progress...) on the main thread This method can be invoked from doinbackground(params...) to publish updates on the main thread, especially UI, while the background computation is still running

Generic types in AsyncTask AsyncTask has three generic types which declare the data type of each parameter public class HelloAsyncTask extends AsyncTask<String, Void, String> { public String result; @Override protected void onpreexecute() { super.onpreexecute(); } @Override protected String doinbackground(string... params) { return result; } @Override protected void onprogressupdate(void... values) { super.onprogressupdate(values); } } @Override protected void onpostexecute(string s) { super.onpostexecute(s); } 14

Example of AsyncTask 15

16 Example of AsyncTask An error is issued. How to revise it?

Example of AsyncTask 17

SERVICE 18

19 Service A Component that should be after an Activity stops Does not provide any UI to user Other Component can start a Service, and this Service will run in the background even though the parent Activity is moved onto other Activity

20 Be careful!!! Background does not mean multithreading Service run in background but is invoked on main thread If Service execute CPU intensive works, the application may cause application not response error i.e., play music, network I/O To avoid this situation, you have to create new thread in Service

Service Workflow 21

22 Manifest of Service Like Activity, Service must be configured in Manifest file as following example <service android:name=.helloservice /> If you need some intent-filter for your Service, you can define it as the case of Activity

23 Types of Service class Service Base class for all services Uses application s main thread by default IntentService Subclass of Service Create a worker thread to handle all of the start request, one at a time

24 Callback methods of Service onstartcommand() Invoke this method by calling startservice() when another component requests that the service be started If you implement this, it is your responsibility to stop the service when its work is complete by calling stopself() or stopservice() onbind() Only used when starting Service Only used when binding Service Invoke this method by calling bindservice() when another component wants to bind with the service You must provide an interface that clients use to communicate with the service by returning an Ibinder You must always implement this method; however, if you don t want to allow binding, you should return null

25 Callback methods of Service oncreate() Invokes this method to perform one-time setup procedures when the service is initially created If the service is already running, this method is not called ondestroy() Invokes this method when the service is no longer used and is being destroyed Your service should implement this to clean up any resources such as threads, registered listeners, or receivers This is the last call that the service receives

26 Start or Bind Service Both startservice() and bindservice() methods start the Service, but have different usage startservice() creates Service which will not communicate with Activity bindservice() creates intercommunicative Service with Activity

27 Binder An object which enables to communicate between Service and Activity Let s look at the example source code

28 Tip for Service in Background As previously mentioned, base Service is not invoked on background thread So, if you want to make your Service run on background thread, use Thread class Thread t = new Thread() { @Override public void run() { // do what you want } }; t.start(); // other works // invoke join() method when parent thread finishes it work, // because child thread will be terminated when parent thread is ended. t.join();

29 Callback methods of IntentService onhandleintent() Invoked on the worker thread with a request to process Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic So, if this code takes a long time, it will hold up other requests to the same IntentSerivce, but it will not hold up anything else When all requests have been handled, the IntentService stops itself, so you should not call stopself()

30 Example of IntentService public class HelloIntentService extends IntentService { /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public HelloIntentService() { super("hellointentservice"); } } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protected void onhandleintent(intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } }

31 [Lab Practice #5] Modify given project to work in following condition Currently application just use the Service as get the data of 777 Change this Service to be used for playing music Music player code will be given Music must be played when bind Service Music must be stopped when unbind Service If you add the pause and resume to your application, you will get extra credit Hint) use mservice variable!

32 [Lab Practice #5] // Initiate music with data from res MediaPlayer mp = MediaPlayer.create(this, R.raw.sample); // Start music mp.start(); // Pause music mp.pause(); int length = mp.getcurrentposition(); // Resume music mp.seekto(length); mp.start(); // Stop music mp.stop();