Android Services. Victor Matos Cleveland State University. Services

Similar documents
App Development for Smart Devices. Lec #4: Services and Broadcast Receivers

Android Service. Lecture 19

Services. Marco Ronchetti Università degli Studi di Trento

Simple Currency Converter

Android. Broadcasts Services Notifications

Notification mechanism

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.

Broadcast receivers. Marco Ronchetti Università degli Studi di Trento

Services. Marco Ronchetti Università degli Studi di Trento

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

MOBILE APPLICATION DEVELOPMENT LECTURE 10 SERVICES IMRAN IHSAN ASSISTANT PROFESSOR

Android Workshop: Model View Controller ( MVC):

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

Manifest.xml. Activity.java

else if(rb2.ischecked()) {

<uses-permission android:name="android.permission.internet"/>

UNDERSTANDING ACTIVITIES

EMBEDDED SYSTEMS PROGRAMMING Android Services

Vienos veiklos būsena. Theory

Android Location Based Services

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

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

Embedded Systems Programming - PA8001

Understanding Intents and Intent Filters

Learn about Android Content Providers and SQLite

App Development for Android. Prabhaker Matet

LifeStreet Media Android Publisher SDK Integration Guide

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH

Real-Time Embedded Systems

INTRODUCTION TO ANDROID

Android Beginners Workshop

LECTURE NOTES OF APPLICATION ACTIVITIES

Android framework overview Activity lifecycle and states

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

EMBEDDED SYSTEMS PROGRAMMING Application Basics

LECTURE 12 BROADCAST RECEIVERS

Security model. Marco Ronchetti Università degli Studi di Trento

Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters

Solving an Android Threading Problem

Applications. Marco Ronchetti Università degli Studi di Trento

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

Android Intents. Notes are based on: Android Developers

Android Data Storage

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

8Messaging SMS MESSAGING.

MAD ASSIGNMENT NO 3. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

1 카메라 1.1 제어절차 1.2 관련주요메서드 1.3 제작철차 서피스뷰를생성하고이를제어하는서피스홀더객체를참조해야함. 매니페스트에퍼미션을지정해야한다.

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

shared objects monitors run() Runnable start()

Android Coding. Dr. J.P.E. Hodgson. August 23, Dr. J.P.E. Hodgson () Android Coding August 23, / 27

Basic UI elements: Defining Activity UI in the code. Marco Ronchetti Università degli Studi di Trento

Embedded Systems Programming - PA8001

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

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

Android Activities. Akhilesh Tyagi

Multiple Activities. Many apps have multiple activities

Table of Content Android Tutorial... 2 Audience... 2 Prerequisites... 2 Copyright & Disclaimer Notice... 2 Overview... 7

Mobila applikationer och trådlösa nät, HI1033, HT2012

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

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

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard.

Tutorial: Setup for Android Development

Database Development In Android Applications

EMBEDDED SYSTEMS PROGRAMMING Android NDK

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

Android Overview. Most of the material in this sec5on comes from h6p://developer.android.com/guide/

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

Saving application preferences

Adaptation of materials: dr Tomasz Xięski. Based on presentations made available by Victor Matos, Cleveland State University.

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

Created By: Keith Acosta Instructor: Wei Zhong Courses: Senior Seminar Cryptography

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed.

Upcoming Assignments Quiz Friday? Lab 5 due today Alpha Version due Friday, February 26

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Xin Pan. CSCI Fall

Create a local SQL database hosting a CUSTOMER table. Each customer includes [id, name, phone]. Do the work inside Threads and Asynctasks.

Android User Interface Android Smartphone Programming. Outline University of Freiburg

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING

App Development for Smart Devices. Lec #7: Audio, Video & Telephony Try It Out

Android permissions Defining and using permissions Component permissions and related APIs

Android Fundamentals - Part 1

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

CS378 -Mobile Computing. Services and Broadcast Receivers

CSE 660 Lab 7. Submitted by: Arumugam Thendramil Pavai. 1)Simple Remote Calculator. Server is created using ServerSocket class of java. Server.

Mobila applikationer och trådlösa nät, HI1033, HT2013

Android HelloWorld - Example. Tushar B. Kute,

Intents. Your first app assignment

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

Android Application Model I

Agenda. The Android GUI Framework Introduction Anatomy A real word example Life cycle Findings

Android User Interface

Advanced Android Development

Practical 1.ListView example

StoppUhr. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start1"

Android Application Development. By : Shibaji Debnath

Mobile and Ubiquitous Computing: Android Programming (part 3)

App Development for Smart Devices. Lec #18: Advanced Topics

COMP61242: Task /04/18

Transcription:

22 Android Victor Matos Cleveland State University Notes are based on: Android Developers http://developer.android.com/index.html 22. Android Android A Service is an application component that runs in the background, not interacting with the user, for an indefinite period of time. Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. can be started with Context.startService() and Context.bindService(). 2 1

22. Android Android Multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to the onstart() method of the Service class), so no matter how many times it is started a service will be stopped once Context.stopService() or stopself() is called. A service can be started and allowed to run until someone stops it or it stops itself. Only one stopservice() call is needed to stop the service, no matter how many times startservice() was called. 3 22. Android Service Life Cycle Like an activity, a service has lifecycle methods that you can implement to monitor changes in its state. But they are fewer than the activity methods only three and they are public, not protected: 1. void oncreate () 2. void onstart (Intent intent) 3. void ondestroy () oncreate onstart ondestroy 4 2

22. Android Service Life Cycle The entire lifetime of a service happens between the time oncreate() is called and the time ondestroy() returns. Like an activity, a service does its initial setup in oncreate(), and releases all remaining resources in ondestroy(). For example, a music playback service could create the thread where the music will be played in oncreate(), and then stop the thread in ondestroy(). 5 22. Android Broadcast Receiver Lifecycle A Broadcast Receiver is an application class that listens for Intents that are broadcast, rather than being sent to a single target application/activity. The system delivers a broadcast Intent to all interested broadcast receivers, which handle the Intent sequentially. 6 3

22. Android Registering a Broadcast Receiver You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml. 7 22. Android Broadcast Receiver Lifecycle A broadcast receiver has a single callback method: void onreceive (Context curcontext, Intent broadcastmsg) 1. When a broadcast message arrives for the receiver, Android calls its onreceive() method and passes it the Intent object containing the message. 2. The broadcast receiver is considered to be active only while it is executing this method. 3. When onreceive() returns, it is inactive. 8 4

22. Android, BroadcastReceivers and the AdroidManifest The manifest of applications using Android must include: 1. A <service> entry for each service used in the application. 2. If the application defines a BroadcastReceiver as an independent class, it must include a <receiver> clause identifying the component. In addition an <intent-filter> entry is needed to declare the actual filter the service and the receiver use. See example 9 22. Android, BroadcastReceivers and the AdroidManifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cis493.demos" android:versioncode="1" android:versionname="1.0.0"> <uses-sdk android:minsdkversion="4"></uses-sdk> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".myservicedriver2 > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <service android:name="myservice2" /> <receiver android:name="mybroadcastreceiver"> <intent-filter> <action android:name = "matos.action.goservice2" /> </intent-filter> </receiver> </application> </manifest> 10 5

22. Android Types of Broadcasts There are two major classes of broadcasts that can be received: 1. Normal broadcasts (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. 2. Ordered broadcasts (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order. 11 22. Android Useful Methods The Driver Assume main activity MyService3Driver wants to interact with a service called MyService3. The main activity is responsible for the following tasks: 1. Start the service called MyService3. Intent intentmyservice = new Intent(this, MyService3.class); Service myservice = startservice(intentmyservice); 2. Define corresponding receiver s filter and register local receiver IntentFilter mainfilter = new IntentFilter("matos.action.GOSERVICE3"); BroadcastReceiver receiver = new MyMainLocalReceiver(); registerreceiver(receiver, mainfilter); 3. Implement local receiver and override its main method public void onreceive(context localcontext, Intent callerintent) 12 6

22. Android Useful Methods The Service Assume main activity MyService3Driver wants to interact with a service called MyService3. The Service uses its onstart method to do the following: 1. Create an Intent with the appropriate broadcast filter (any number of receivers could match it). Intent myfilteredresponse = new Intent("matos.action.GOSERVICE3"); 2. Prepare the extra data ( myservicedata ) to be sent with the intent to the receiver(s) Object msg = some user data goes here; myfilteredresponse.putextra("myservicedata", msg); 3. Release the intent to all receivers matching the filter sendbroadcast(myfilteredresponse); 13 22. Android Useful Methods The Driver (again) Assume main activity MyService3Driver wants to interact with a service called MyService3. The main activity is responsible for cleanly terminating the service. Do the following 1. Assume intentmyservice is the original Intent used to start the service. Calling the termination of the service is accomplished by the method stopservice(new Intent(intentMyService) ); 2. Use the service s ondestroy method to assure that all of its running threads are terminated and the receiver is unregistered. unregisterreceiver(receiver); 14 7

22. Android Example 1. A very Simple Service The main application starts a service. The service prints lines on the DDMS LogCat until the main activity stops the service. No IPC occurs in the example. // a simple service is started & stopped package cis493.demos; import android.app.activity; import android.content.componentname; import android.content.intent; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.*; public class ServiceDriver1 extends Activity { TextView txtmsg; Button btnstopservice; ComponentName service; Intent intentmyservice; 15 22. Android Example 1. cont. public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); txtmsg = (TextView) findviewbyid(r.id.txtmsg); intentmyservice = new Intent(this, MyService1.class); service = startservice(intentmyservice); btnstopservice = (Button) findviewbyid(r.id.btnstopservice); btnstopservice.setonclicklistener(new OnClickListener() { public void onclick(view v) { try { stopservice((intentmyservice) ); txtmsg.settext("after stoping Service: \n" + service.getclassname()); catch (Exception e) { Toast.makeText(getApplicationContext(), e.getmessage(), 1).show(); ); 16 8

22. Android Example 1. cont. //non CPU intensive service running the main task in its main thread package cis493.demos; import android.app.service; import android.content.intent; import android.os.ibinder; import android.util.log; public class MyService1 extends Service { public IBinder onbind(intent arg0) { return null; public void oncreate() { super.oncreate(); Log.i ("<<MyService1-onStart>>", "I am alive-1!"); public void onstart(intent intent, int startid) { super.onstart(intent, startid); Log.i ("<<MyService1-onStart>>", "I did something very quickly"); public void ondestroy() { super.ondestroy(); Log.i ("<<MyService1-onDestroy>>", "I am dead-1"); //MyService1 17 22. Android Example 1. cont. According to the Log 1. Main Activity is started (no displayed yet) 2. Service is started (oncreate, onstart) 3. Main Activity UI is displayed 4. User stops Service 18 9

22. Android Example 1. cont. Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cis493.demos" android:versioncode="1" android:versionname="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".servicedriver1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <service android:name=".myservice1"> </service> </application> <uses-sdk android:minsdkversion="4" /> </manifest> 19 22. Android Example 1. cont. Layout <?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout android:id="@+id/widget32" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <EditText android:id="@+id/txtmsg" android:layout_width="fill_parent" android:layout_height="120px" android:textsize="18sp" android:layout_x="0px" android:layout_y="57px" > </EditText> <Button android:id="@+id/btnstopservice" android:layout_width="151px" android:layout_height="wrap_content" android:text=" Stop Service" android:layout_x="43px" android:layout_y="200px" > </Button> </AbsoluteLayout> 20 10

22. Android Example3. Realistic Activity-Service Interaction 1. The main activity starts the service and registers a receiver. 2. The service is slow, therefore it runs in a parallel thread its time consuming task. 3. When done with a computing cycle, the service adds a message to an intent. 4. The intent is broadcasted using the filter: matos.action.goservice3. 5. A BroadcastReceiver (defined inside the main Activity) uses the previous filter and catches the message (displays the contents on the main UI ). 6. At some point the main activity stops the service and finishes executing. 21 22. Android Example 2. Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget32" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <EditText android:id="@+id/txtmsg" android:layout_width="fill_parent" android:layout_height="120px" android:textsize="12sp" > </EditText> <Button android:id="@+id/btnstopservice" android:layout_width="151px" android:layout_height="wrap_content" android:text="stop Service" > </Button> </LinearLayout> 22 11

22. Android Example 2. Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cis493.demos" android:versioncode="1" android:versionname="1.0.0"> <uses-sdk android:minsdkversion="4"></uses-sdk> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".myservicedriver3" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <service android:name="myservice3"> </service> </application> </manifest> 23 22. Android Example 2. Main Activity // Application logic and its BroadcastReceiver in the same class package cis493.demos; import java.util.date; import android.app.activity; import android.content.broadcastreceiver; import android.content.componentname; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.os.systemclock; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.*; public class MyServiceDriver3 extends Activity { TextView txtmsg; Button btnstopservice; ComponentName service; Intent intentmyservice; BroadcastReceiver receiver; 24 12

22. Android Example 2. Main Activity public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); txtmsg = (TextView) findviewbyid(r.id.txtmsg); intentmyservice = new Intent(this, MyService3.class); service = startservice(intentmyservice); start txtmsg.settext("myservice3 started - (see DDMS Log)"); btnstopservice = (Button) findviewbyid(r.id.btnstopservice); btnstopservice.setonclicklistener(new OnClickListener() { public void onclick(view v) { try { stopservice(new Intent(intentMyService) ); stop txtmsg.settext("after stoping Service: \n" + service.getclassname()); catch (Exception e) { e.printstacktrace(); ); 25 22. Android Example 2. Main Activity // register & define filter for local listener IntentFilter mainfilter = new IntentFilter("matos.action.GOSERVICE3"); receiver = new MyMainLocalReceiver(); registerreceiver(receiver, mainfilter); //oncreate register //////////////////////////////////////////////////////////////////////// protected void ondestroy() { super.ondestroy(); try { stopservice(intentmyservice); unregister unregisterreceiver(receiver); catch (Exception e) { Log.e ("MAIN3-DESTROY>>>", e.getmessage() ); Log.e ("MAIN3-DESTROY>>>", "Adios" ); //ondestroy 26 13

22. Android Example 2. Main Activity ////////////////////////////////////////////////////////////////////// // local (embedded) RECEIVER public class MyMainLocalReceiver extends BroadcastReceiver { public void onreceive(context localcontext, Intent callerintent) { Get String servicedata = callerintent.getstringextra("servicedata"); data Log.e ("MAIN>>>", servicedata + " -receiving data " + SystemClock.elapsedRealtime() ); String now = "\n" + servicedata + " --- " + new Date().toLocaleString(); txtmsg.append(now); //MyMainLocalReceiver //MyServiceDriver4 27 22. Android Example 2. The Service // Service3 uses a thread to run slow operation package cis493.demos; import android.app.service; import android.content.intent; import android.os.ibinder; import android.util.log; public class MyService3 extends Service { boolean isrunning = true; public IBinder onbind(intent arg0) { return null; public void oncreate() { super.oncreate(); 28 14

22. Android Example 2. The Service public void onstart(intent intent, int startid) { super.onstart(intent, startid); Log.e ("<<MyService3-onStart>>", "I am alive-3!"); // we place the slow work of the service in its own thread // so the caller is not hung up waiting for us Thread triggerservice = new Thread ( new Runnable(){ long startingtime = System.currentTimeMillis(); long tics = 0; public void run() { for(int i=0; (i< 120) & isrunning; i++) { //at most 10 minutes try { //fake that you are very busy here tics = System.currentTimeMillis() - startingtime; Set filter Intent myfilteredresponse = new Intent("matos.action.GOSERVICE3"); String msg = i + " value: " + tics; myfilteredresponse.putextra("servicedata", msg); broadcasting sendbroadcast(myfilteredresponse); Thread.sleep(1000); //five seconds catch (Exception e) { e.printstacktrace(); //for //run ); triggerservice.start(); //onstart 29 22. Android Example 2. The Service public void ondestroy() { super.ondestroy(); Log.e ("<<MyService3-onDestroy>>", "I am dead-3"); isrunning = false; //ondestroy Stop thread //MyService3 30 15

22. Android Questions 31 16