Threads and Services. Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android.

Slides:



Advertisements
Similar presentations
Google Android Introduction to Mobile Computing. Android is part of the build a better phone process Open Handset Alliance produces Android Comprises.
Advertisements

Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
Programming with Android: Notifications, Threads, Services
Android architecture overview
CSS216 MOBILE PROGRAMMING Android, Chapter 9 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
The Activity Class 1.  One application component type  Provides a visual interface for a single screen  Typically supports one thing a user can do,
Notifications & Alarms.  Notifications  Alarms.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
1 Working with the Android Services Nilanjan Banerjee Mobile Systems Programming University of Arkansas Fayetteville, AR
@2011 Mihail L. Sichitiu1 Android Introduction Hello Views Part 1.
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Mobile Programming Lecture 16 The Facebook API. Agenda The Setup Hello, Facebook User Facebook Permissions Access Token Logging Out Graph API.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Android Activities 1. What are Android Activities? Activities are like windows in an Android application An application can have any number of activities.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Homescreen Widgets Demystified Pearl AndroidTO // Oct 26, 2010.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Integrating with Android Services. Introduction  Android has numerous built-in functionality that can be called from within your applications  SMS/MMS.
Mobile Programming Lecture 6
DUE Hello World on the Android Platform.
CS378 - Mobile Computing Intents.
로봇 모니터링 2/2 UNIT 21 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Broadcasting Service 2.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
Android Accessing GPS Ken Nguyen Clayton State University 2012.
1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
Activity Android Club Agenda Hello Android application Application components Activity StartActivity.
@2010 Mihail L. Sichitiu1 Android Introduction Hello Threads.
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang.
Android Application Lifecycle and Menus
Lecture 2: Android Concepts
Class on Fragments & threads. Fragments fragment is a modular section of an activity, which has its own lifecycle, receives its own input events, and.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
David Sutton SMS TELEPHONY IN ANDROID. OUTLINE  This week’s exercise, an SMS Pub Quiz  Simulating telephony on an emulator  Broadcast Intents and broadcast.
Lecture 5: Location Topics: Google Play Services, Location API Date: Feb 16, 2016.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
Introduction to android
Android Application -Architecture.
Concurrency in Android
Lecture 2: Android Concepts
Android Application Development 1 6 May 2018
GUI Programming Fundamentals
Android – Event Handling
Activities, Fragments, and Events
Android Notifications
ITEC535 – Mobile Programming
תכנות ב android אליהו חלסצ'י.
Developing Android Services
CIS 470 Mobile App Development
Activities and Intents
Android Topics Threads and the MessageQueue
Android Notifications
Service Services.
Notifying from the Background
Lecture 6: Process, Thread, Task
Lecture 2: Android Concepts
// Please Setting App_name to Send Successful
Activities, Fragments, and Intents
CIS 470 Mobile App Development
Presentation transcript:

Threads and Services

Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android –Threads Run something in the background while user interacts with UI –Services Regularly or continuously perform actions that don’t require a UI

Threads Recall that Android ensures responsive apps by enforcing a 5 second limit on Activities Sometimes we need to do things that take longer than 5 seconds, or that can be done while the user does something else

Threads Activities, Services, and Broadcast Receivers run on the main application thread We can start background/child threads to do things for us

Threads private void methodInAndroidClass() { Thread thread = new Thread(null, doSomething, “Background”); Thread.start(); } private Runnable doSomething = new Runnable() { public void run() { /* do the something here */ } }; private void methodInAndroidClass() { new Thread(){ public void run() {/* do the something here */ } }.start(); }

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Thread() { public void run() { String maps = null; try { URL updateURL = new URL(" URLConnection conn = updateURL.openConnection(); int contentLength = conn.getContentLength(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is,1024); ByteArrayBuffer baf = new ByteArrayBuffer(contentLength); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. } catch (Exception e) {} } }.start(); } Get data from web in background Now we want to display data on screen

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView hello = (TextView)this.findViewById(R.id.hellotv); hello.setText("testing"); new Thread() { public void run() { String maps = null; try { URL updateURL = new URL(" URLConnection conn = updateURL.openConnection(); int contentLength = conn.getContentLength(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is,1024); ByteArrayBuffer baf = new ByteArrayBuffer(contentLength); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. } catch (Exception e) {} TextView hello = (TextView)findViewById(R.id.hellotv); hello.setText(maps); }}.start(); CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Android Thread Constraints Child threads cannot access UI elements (views); these must be accessed through the main thread What to do? –Give results to main thread and let it use results You can set a flag in the thread, then add the menu item dynamically in Activity.onPrepareOptionsMenu

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView hello = (TextView)this.findViewById(R.id.hellotv); hello.setText("testing"); new Thread() { public void run() { String maps = null; try { URL updateURL = new URL(" URLConnection conn = updateURL.openConnection(); int contentLength = conn.getContentLength(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is,1024); ByteArrayBuffer baf = new ByteArrayBuffer(contentLength); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. } catch (Exception e) {} hello.setText(maps); }}.start();

Post to GUI Thread Handler allows you to post Messages and Runnable objects to threads –These can be scheduled to run at some point in the future, or enqueued for another thread

public class BackgroundDemos extends Activity { private Handler handler = new Handler(); private String maps = null; TextView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); hello = (TextView)this.findViewById(R.id.hellotv); hello.setText("testing"); new Thread() { public void run() { try { URL updateURL = new URL(" //code omitted here maps = new String(baf.toByteArray()); //Convert the Bytes read to a String. handler.post(doUpdateMaps); } catch (Exception e) {} } }.start(); } private Runnable doUpdateMaps = new Runnable() { public void run() { hello.setText(maps); } };}

Services Services are like Activities, but without a UI Services are not intended as background threads –Think of a media player where the song keeps playing while the user looks for more songs to play or uses other apps –Don’t think of a cron job (e.g. run every day at 3am), use Alarms to do this Several changes in 2.0 related to Services –See developers.blogspot.com/2010/02/service-api-changes- starting-with.html

Add to AndroidManifest.xml Create the Service class public class NewMapService extends Service public void onCreate() { public void onStart(Intent intent, int startId) { //do something public IBinder onBind(Intent intent) { return null; }

Other alternatives in text public class MyActivity extends Activity public void onCreate() { … startService(new Intent(this, NewMapService.class); public void onStop() { … stopService(new Intent(this, NewMapService.class)); } Start/Stop the Service

Status Bar Notifications NotificationManager nm = (NotificationManager)getSystemService( Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, "NewMaps",System.currentTimeMillis()); String expandedTitle = "New Map Service"; String expandedText = "New Map Service is running"; Intent i = new Intent(this, NewMapService.class); PendingIntent launchIntent = PendingIntent.getActivity( getApplicationContext(), 0, i, 0); notification.setLatestEventInfo(getApplicationContext(), expandedTitle, expandedText, launchIntent); nm.notify(1,notification); nm.cancel(1); //cancel a notification (id/parameters must match)

Other Notification Sounds Vibration Flashing lights Ongoing and Insistent