안드로이드2_09

Similar documents
안드로이드2_14

슬라이드 1

13ÀåÃß°¡ºÐ

( )부록

어댑터뷰

PowerPoint 프레젠테이션

콘텐츠 PowerPoint 디자인

rosaec_workshop_talk

01장

03장

안드로이드기본 11 차시어댑터뷰 1 학습목표 어댑터뷰가무엇인지알수있다. 리스트뷰와스피너를사용하여데이터를출력할수있다. 2 확인해볼까? 3 어댑터뷰 1) 학습하기 어댑터뷰 - 1 -

2 Application Name: Day10_yhg <LinearLayout android:layout_weight="3" > /> an

02 C h a p t e r Java

JMF3_심빈구.PDF

[ 그림 8-1] XML 을이용한옵션메뉴설정방법 <menu> <item 항목ID" android:title=" 항목제목 "/> </menu> public boolean oncreateoptionsmenu(menu menu) { getme

rmi_박준용_final.PDF

2) 활동하기 활동개요 활동과정 [ 예제 10-1]main.xml 1 <LinearLayout xmlns:android=" 2 xmlns:tools="

Android Programming

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

OpenCV와 함께하는 컴퓨터 비전 프로그래밍 캠프

학습목표 선언하여디자인을하는방법을이해하고, 실행할수있다. 시작화면을만드는방법과대체리소스를사용하는방법을이해하고실행할수있다. About 과같은상자를구현하고, 테마를적용하는법을이해하고실행할수있다.

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

비긴쿡-자바 00앞부속

슬라이드 1

12-file.key

구글안드로이드프로그래밍액티비티, 인텐트수신자, 그리고서비스 안드로이드애플리케이션의구성요소에는액티비티, 인텐트수신자, 서비스, 컨텐트제공자가있다. 이번호에서는사용자인터페이스를위한액티비티와백그라운드서비스를위한인텐트수신자, 그리고서비스의라이프사이클과활용법에대해살펴보도록하자.

자바-11장N'1-502

PowerPoint 프레젠테이션

슬라이드 1

헬로, 안드로이드 13 주차 SQL 활용하기 (2) 강대기동서대학교컴퓨터정보공학부

歯JavaExceptionHandling.PDF

Java XPath API (한글)

신림프로그래머_클린코드.key

슬라이드 1

SKT UCC DRM

[ 그림 7-1] 프로젝트 res 폴더 이미지뷰 [ 예제 7-1] 이미지뷰 1 <LinearLayout 2 ~~~~ 중간생략 ~~~~ 3 android:orientation="vertical" > 4 <ImageView

JMF2_심빈구.PDF


Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

Microsoft PowerPoint - 15주차(최종).pptx

학습목표 메뉴를추가하는방법을이해하고실습할수있다. 프로그램의기본설정 (settings) 을정의하는방법을알고실습할수있다. 대화상자를여는방법을알고실습할수있다. 로그메시지로디버깅하는방법을이해한다. 디버거로디버깅하는방법을이해한다.

9 차시고급위젯다루기 1 학습목표 날짜 / 시간과관련된위젯을배운다. 웹뷰를사용하여간단한웹브라우저기능을구현한다. 매니패스트파일의설정법을배운다. 2 확인해볼까? 3 날짜 / 시간위젯 1) 활동하기 활동개요

Microsoft PowerPoint - 04-UDP Programming.ppt

PowerPoint 프레젠테이션

REMON Android SDK GUIDE (SDK Version 1.4.1) 1 / 25

Microsoft PowerPoint App Fundamentals[Part2].pptx

01-OOPConcepts(2).PDF

mytalk

안드로이드 서비스

SMART ZONE CAST ANDROID SDK 적용가이드 NIT

ch09

05-class.key

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

리니어레이아웃 - 2 -

Chap12

슬라이드 1

50_1953.pdf

보가태그다. 태그정보를뮤직플레이어에서활용해곡명과가수정보를출력하는것이다. 안드로이드뮤직플레이어도태그정보를활용한다. 태그정보는문자열로, 글자깨짐현상은글자의인코딩과디코딩의문제로보인다. 따라서원인은다음과같이 2가지로분석할수있다. MP3 파일에서인코딩설정이잘못됨. 안드로이드플랫

09-interface.key

OOP 소개

Microsoft PowerPoint - 4주차_Android_UI구현.ppt [호환 모드]

슬라이드 1

3ÆÄÆ®-11

위젯과레이아웃위젯은 View 클래스를상속해화면디스플레이와이벤트처리를할수있도록구현된스크린구성의최소단위를말한다. android.widget 패키지에는여러유형의위젯들이포함되어있다. TextView, ImageView, Button, ImageButton 등은가장간단한위젯들이

헬로, 안드로이드 11 주차 위치파악하기와감지하기 강대기동서대학교컴퓨터정보공학부

자바GUI실전프로그래밍2_장대원.PDF

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

자바 프로그래밍

Ext JS À¥¾ÖÇø®ÄÉÀ̼ǰ³¹ß-³¹Àå.PDF

이것은리스트뷰의 setadapter 메소드에잘표현되어있습니다. setadapter 는리스트뷰에사용할데이터객체를넘겨주는메소드입니다. 일반적으로생각한다면 ArrayAdapter 객체를생성하여사용할데이터를저장할것이고데이터가저장된 ArrayAdapter 객체를 setadapt

쉽게 풀어쓴 C 프로그래밊

Modern Javascript

자바로

MapView

MasoJava4_Dongbin.PDF

2파트-07

목차 BUG DEQUEUE 의 WAIT TIME 이 1 초미만인경우, 설정한시간만큼대기하지않는문제가있습니다... 3 BUG [qp-select-pvo] group by 표현식에있는컬럼을참조하는집합연산이존재하지않으면결괏값오류가발생할수있습니다... 4

FileMaker ODBC and JDBC Guide

Microsoft PowerPoint UI-Event.Notification(1.5h).pptx

Polly_with_Serverless_HOL_hyouk

5장.key

교육2 ? 그림

Spring Data JPA Many To Many 양방향 관계 예제

PowerPoint 프레젠테이션

Table of Contents 1. 분석 정보 i. 분석 대상 ii. 분석 환경 2. 동적 분석 3. 정적 분석 4. 결론 5. 치료 방법 Android-Trojan/FakeInst 악성코드 분석 보고서 Page 2 / 13

Spring Boot/JDBC JdbcTemplate/CRUD 예제

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사)

(......).hwp

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Microsoft PowerPoint - 03-TCP Programming.ppt

13주-14주proc.PDF

기술문서 작성 XXE Attacks 작성자 : 인천대학교 OneScore 김영성 I. 소개 2 II. 본문 2 가. XML external entities 2 나. XXE Attack 3 다. 점검방법 3 라.

DocsPin_Korean.pages

SKT SmartZoneCast Agent 개발자 적용가이드_180116

07 자바의 다양한 클래스.key

untitled

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

NoSQL

Transcription:

Service..,.,....

Chapter 09 GUI,. ( ) Thread AsyncTask... Toasts non modal,....,,.,.. Alarms.,,.,( ).,,,.,,.

397,,.,,.... ( ).. (, ).,.. MP3..,,. startservice.,. Service., 9 1 onbind oncreate. import android.app.service; import android.content.intent;

Chapter 09 import android.os.ibinder; public class MyService extends Service { public void oncreate() { // TODO:. public IBinder onbind(intent intent) { // TODO:. return null; onstartcommand. startservice,.. onstartcommand 2.0 onstart. onstartcommand onstart, stopservice stopself. 9 1 onstartcommand... public int onstartcommand(intent intent, int flags, int startid) { // TODO:. return Service.START_STICKY;., onstartcommand GUI. onstartcommand

399, ( ). onstartcommand, Service. START_STICKY. 2.0 onstart. onstartcommand., onstartcommand null. (startservice stopservice ).. START_NOT_STICKY. stopself., pending start calls. startservice, onstartcommand., network polling.. START_REDELIVER_INTENT.., stopself. onstartcommand,.

Chapter 09 stopservice stopself.. onstart onstart onstartcommand START_STICKY onstartcommand. startservice. START_STICKY null, START_ REDELIVER_INTENT. flag. 9 2. START_FLAG_REDELIVERY. stopself. START_FLAG_RETRY. START_STICKY. public int onstartcommand(intent intent, int flags, int startid) { if ((flags & START_FLAG_RETRY) == 0) { // TODO:. else { // TODO:. return Service.START_STICKY;

401. application <service>. requires-permission. service. <service android:enabled="true" android:name=".myservice"/> stopself. stopself. startservice, startid stopself. stopself(startid);... startservice.,., startservice SecurityException. onstart. 9 3.

Chapter 09 //. Intent myintent = new Intent(MyService.ORDER_PIZZA); myintent.putextra("topping", "Margherita"); startservice(myintent); //. startservice(new Intent(this, MyService.class)); MyService ORDER_PIZZA ORDER_PIZZA stopservice. 9 4, startservice. ComponentName service = startservice(new Intent(this, BaseballWatch.class)); //. stopservice(new Intent(this, service.getclass())); //. try { Class serviceclass = Class.forName(service.getClassName()); stopservice(new Intent(this, serviceclass)); catch (ClassNotFoundException e) { startservice onstartcommand. startservice. startservice stopservice. 5 6, 7, 8..

403 1. Service EarthquakeService. package com.paad.earthquake; import android.app.service; import android.content.intent; import android.os.ibinder; import java.util.timer; import java.util.timertask; public class EarthquakeService extends Service { public void oncreate() { // TODO:, GUI. public IBinder onbind(intent intent) { return null; 2. application service. <service android:enabled="true" android:name=".earthquakeservice"/> 3. Earthquake refreshearthquakes addnewquake Earthquake Service. addquaketoarray loadquakesfromprovider ( Earthquake ). EarthquakeService earthquakes.

Chapter 09 private void addnewquake(quake _quake) { ContentResolver cr = getcontentresolver(); // // where. String w = EarthquakeProvider.KEY_DATE + " = " + _quake.getdate().gettime(); //. Cursor c = cr.query(earthquakeprovider.content_uri, null, w, null, null); if (c.getcount()==0){ ContentValues values = new ContentValues(); values.put(earthquakeprovider.key_date, _quake.getdate().gettime()); values.put(earthquakeprovider.key_details, _quake.getdetails()); double lat = _quake.getlocation().getlatitude(); double lng = _quake.getlocation().getlongitude(); values.put(earthquakeprovider.key_location_lat, lat); values.put(earthquakeprovider.key_location_lng, lng); values.put(earthquakeprovider.key_link, _quake.getlink()); values.put(earthquakeprovider.key_magnitude, _quake.getmagnitude()); cr.insert(earthquakeprovider.content_uri, values); c.close(); private void refreshearthquakes() { // XML. URL url; try { String quakefeed = getstring(r.string.quake_feed); url = new URL(quakeFeed); URLConnection connection; connection = url.openconnection(); HttpURLConnection httpconnection = (HttpURLConnection)connection; int responsecode = httpconnection.getresponsecode(); if (responsecode == HttpURLConnection.HTTP_OK) { InputStream in = httpconnection.getinputstream();

405 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newdocumentbuilder(); //. Document dom = db.parse(in); Element docele = dom.getdocumentelement(); //. NodeList nl = docele.getelementsbytagname("entry"); if (nl!= null && nl.getlength() > 0) { for (int i = 0 ; i < nl.getlength(); i++) { Element entry = (Element)nl.item(i); Element title; title = (Element)entry.getElementsByTagName("title").item(0); Element g = (Element)entry.getElementsByTagName("georss:point").item(0); Element when = (Element)entry.getElementsByTagName("updated").item(0); Element link = (Element)entry.getElementsByTagName("link").item(0); String details = title.getfirstchild().getnodevalue(); String hostname = "http://earthquake.usgs.gov"; String linkstring = hostname + link.getattribute("href"); String point = g.getfirstchild().getnodevalue(); String dt = when.getfirstchild().getnodevalue(); SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); Date qdate = new GregorianCalendar(0,0,0).getTime(); try { qdate = sdf.parse(dt); catch (ParseException e) { e.printstacktrace(); String[] location = point.split(" "); Location l = new Location("parsed"); l.setlatitude(double.parsedouble(location[0])); l.setlongitude(double.parsedouble(location[1])); String magnitudestring = details.split(" ")[1];

Chapter 09 int end = magnitudestring.length()-1; double magnitude = Double.parseDouble(magnitudeString.substring(0, end)); details = details.split(",")[1].trim(); Quake quake = new Quake(qdate, details, l, magnitude, linkstring); //. addnewquake(quake); catch (MalformedURLException e) { e.printstacktrace(); catch (IOException e) { e.printstacktrace(); catch (ParserConfigurationException e) { e.printstacktrace(); catch (SAXException e) { e.printstacktrace(); finally { 4. Earthquake refreshearthquakes. EarthquakeService. private void refreshearthquakes() { startservice(new Intent(this, EarthquakeService.class)); 5. EarthquakeService. onstartcommand oncreate. onstartcommand START_STICKY..,..

407 6 Shared Preferences. private Timer updatetimer; private int minimummagnitude = 0; private boolean autoupdate = false; private int updatefreq = 0; public int onstartcommand(intent intent, int flags, int startid) { // Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); autoupdate = prefs.getboolean(preferences.pref_auto_update, false); minimummagnitude = Integer.parseInt(prefs.getString(Preferences.PREF_MIN_MAG, "0")); updatefreq = Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0")); updatetimer.cancel(); if(autoupdate) { updatetimer = new Timer("earthquakeUpdates"); updatetimer.scheduleatfixedrate(new TimerTask() { public void run() { refreshearthquakes();, 0, updatefreq*60*1000); import import android.content.sharedpreferences; import android.content.res.resources; import android.preference.preferencemanager;

Chapter 09 refreshearthquakes(); ; return Service.START_STICKY; public void oncreate() { updatetimer = new Timer("earthquakeUpdates"); 6. EarthquakeService. Earthquake EarthquakeMap. EarthquakeService.. 6.1. addnewquake announcenewquake. public static final String NEW_EARTHQUAKE_FOUND = "New_Earthquake_Found"; private void addnewquake(quake _quake) { ContentResolver cr = getcontentresolver(); // // where. String w = EarthquakeProvider.KEY_DATE + " = " + _quake.getdate().gettime(); //. if (cr.query(earthquakeprovider.content_uri,

409 null, w, null, null).getcount()==0){ ContentValues values = new ContentValues(); values.put(earthquakeprovider.key_date, _quake.getdate().gettime()); values.put(earthquakeprovider.key_details, _quake.getdetails()); double lat = _quake.getlocation().getlatitude(); double lng = _quake.getlocation().getlongitude(); values.put(earthquakeprovider.key_location_lat, lat); values.put(earthquakeprovider.key_location_lng, lng); values.put(earthquakeprovider.key_link, _quake.getlink()); values.put(earthquakeprovider.key_magnitude, _quake.getmagnitude()); cr.insert(earthquakeprovider.content_uri, values); announcenewquake(_quake); private void announcenewquake(quake quake) { 6.2. announcenewquake. private void announcenewquake(quake quake) { Intent intent = new Intent(NEW_EARTHQUAKE_FOUND); intent.putextra("date", quake.getdate().gettime()); intent.putextra("details", quake.getdetails()); intent.putextra("longitude", quake.getlocation().getlongitude()); intent.putextra("latitude", quake.getlocation().getlatitude()); intent.putextra("magnitude", quake.getmagnitude()); sendbroadcast(intent); 7. EarthquakeService. Earthquake announcenewquake. 7.1. Earthquake BroadcastReceiver Earthquake Receiver. onreceive

Chapter 09 loadquakesfromprovider earthquakes. public class EarthquakeReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { loadquakesfromprovider(); 7.2. onresume 7.1. onpause, onresume. EarthquakeReceiver receiver; public void onresume() { IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); loadquakesfromprovider(); super.onresume(); public void onpause() { unregisterreceiver(receiver); super.onpause(); import import android.content.broadcastreceiver; import import android.content.intentfilter;

411 7.3. EarthquakeMap, requery MapView. EarthquakeReceiver receiver; public void onresume() { earthquakecursor.requery(); IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); super.onresume(); public void onpause() { earthquakecursor.deactivate(); super.onpause(); public class EarthquakeReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { earthquakecursor.requery(); MapView earthquakemap = (MapView)findViewById(R.id.map_view); earthquakemap.invalidate(); Earthquake. Earthquake. import import android.content.broadcastreceiver; import android.content.intentfilter;

Chapter 09, GUI. Force Close....,.... 9 5 onbind. private final IBinder binder = new MyBinder(); public IBinder onbind(intent intent) { return binder; public class MyBinder extends Binder { MyService getservice() { return MyService.this; ServiceConnection., 9 6 ServiceConnection

413 onserviceconnected onservicedisconnected. //. private MyService servicebinder; //. private ServiceConnection mconnection = new ServiceConnection() { public void onserviceconnected(componentname classname, IBinder service) { //. servicebinder = ((MyService.MyBinder)service).getService(); ; public void onservicedisconnected(componentname classname) { //. servicebinder = null; bindservice. ServiceConnection. 9 6. public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); //. Intent bindintent = new Intent(MyActivity.this, MyService.class); bindservice(bindintent, mconnection, Context.BIND_AUTO_CREATE);, onserviceconnected (servicebinder) public.,.

Chapter 09,. AIDL. AIDL. AIDL OS. AIDL 15. 3.,,.,... startforeground. (, ).. startforeground 9 7 ongoing Notification ( )..

415 int NOTIFICATION_ID = 1; Intent intent = new Intent(this, MyActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0)); Notification notification = new Notification(R.drawable.icon, " ", System.currentTimeMillis()); notification.setlatesteventinfo(this, " ", " ", pi); notification.flags = notification.flags Notification.FLAG_ONGOING_EVENT; startforeground(notification_id, notification); 9 7 setlatesteventinfo..,., 9 8 stopforeground.. //. stopforeground(true); setforeground

Chapter 09.. AsyncTask, GUI. Thread Handler GUI UI.. 2. ( ) 5 onreceive 10..,,,. AsyncTask. AsyncTask GUI. UI. AsyncTask,,. AsyncTask, UI.

417 9 9 AsyncTask. AsyncTask execute,,. AsyncTask<[ ], [ ], [ ]>,, Void. private class MyAsyncTask extends AsyncTask<String, Integer, Integer> { protected void onprogressupdate(integer... progress) { // [... UI... ] protected void onpostexecute(integer... result) { // [... UI... ] protected Integer doinbackground(string... parameter) { int myprogress = 0; // [..., myprogress... ] publishprogress(myprogress); // [...... ] // onpostexecute. return result; 9 9 AsyncTask.

Chapter 09 doinbackground AsyncTask.. UI. publishprogress onprogressupdate UI. onpostexecute UI. onprogressupdate UI. doinbackground publishprogress. GUI. UI. onpostexecute. doinbackground UI. GUI. UI., 9 10 execute. execute AsyncTask. new MyAsyncTask().execute("inputString1", "inputstring2"); AsyncTask execute AsyncTask execute

419 EarthquakeService XML AsyncTask. 1. EarthquakeLookupTask AsyncTask. Void, Quake. doinbackground, onprogressupdate, onpostexecute. public class EarthquakeLookupTask extends AsyncTask<Void, Quake, Void> { protected Void doinbackground(void... params) { return null; protected void onprogressupdate(quake... values) { super.onprogressupdate(values); protected void onpostexecute(void result) { super.onpostexecute(result); 2. refreshearthquakes doinbackground. publishprogress. publishprogress Quake. null. protected Void doinbackground(void... params) { [... XML... ] //. addnewquake(quake); publishprogress(quake); import import android.os.asynctask;

Chapter 09 [...... ] return null; 3. refreshearthquakes. Earthquake LookupTask... EarthquakeLookupTask lastlookup = null; private void refreshearthquakes() { if (lastlookup == null lastlookup.getstatus().equals(asynctask.status.finished)) { lastlookup = new EarthquakeLookupTask(); lastlookup.execute((void[])null); AsyncTask.. UI GUI. Handler java.lang.thread. 9 11. // GUI. private void mainprocessing() { //.

421 Thread thread = new Thread(null, dobackgroundthreadprocessing, "Background"); thread.start(); // Runnable. private Runnable dobackgroundthreadprocessing = new Runnable() { public void run() { backgroundthreadprocessing(); ; //. private void backgroundthreadprocessing() { [...... ] GUI (GUI). GUI. GUI. runonuithread. runonuithread UI. runonuithread(new Runnable() { public void run() { // TODO:. ); ( ) Handler Handler.

Chapter 09 Handler post. 9 13 GUI. //. private Handler handler = new Handler(); private void mainprocessing() { Thread thread = new Thread(null, dobackgroundthreadprocessing, "Background"); thread.start(); private Runnable dobackgroundthreadprocessing = new Runnable() { public void run() { backgroundthreadprocessing(); ; //. private void backgroundthreadprocessing() { [...... ] handler.post(doupdategui); // GUI Runnable. private Runnable doupdategui = new Runnable() { public void run() { updategui(); ; private void updategui() { [... GUI... ] Handler postdelayed GUI, postattime.

423.,..,. Toast static maketext. maketext,, (LENGTH_SHORT LENGTH_LONG). 9 14 show. Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, msg, duration); toast.show(); 9 1 9 14. 2..

Chapter 09,.. 9 15 setgravity. Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, msg, duration); int offsetx = 0; int offsety = 0; toast.setgravity(gravity.bottom, offsetx, offsety); toast.show();. setview ( ). transient message window mechanism., 9 16 4 CompassView TextView. Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, msg, duration); toast.setgravity(gravity.top, 0, 0); LinearLayout ll = new LinearLayout(context); ll.setorientation(linearlayout.vertical); TextView mytextview = new TextView(context);

425 CompassView cv = new CompassView(context); mytextview.settext(msg); int lheight = LinearLayout.LayoutParams.FILL_PARENT; int lwidth = LinearLayout.LayoutParams.WRAP_CONTENT; ll.addview(cv, new LinearLayout.LayoutParams(lHeight, lwidth)); ll.addview(mytextview, new LinearLayout.LayoutParams(lHeight, lwidth)); ll.setpadding(40, 50, 0, 50); toast.setview(ll); toast.show(); 9 2.

Chapter 09 GUI GUI. cross thread exception. 9 17 GUI. private void mainprocessing() { Thread thread = new Thread(null, dobackgroundthreadprocessing, "Background"); thread.start(); private Runnable dobackgroundthreadprocessing = new Runnable() { public void run() { backgroundthreadprocessing(); ; private void backgroundthreadprocessing() { handler.post(doupdategui); // GUI Runnable. private Runnable doupdategui = new Runnable() { public void run() { Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_SHORT; Toast.makeText(context, msg, duration).show(); ;

427..... LED.. audible alerts..,,,. ( ).

Chapter 09...,....,,., 9 3.. 9 18 getsystemservice. String svcname = Context.NOTIFICATION_SERVICE;

429 NotificationManager notificationmanager; notificationmanager = (NotificationManager)getSystemService(svcName);,,.. 1. 2. 3.. Notification LED,,. 9 19 Notification, ticker text. //. int icon = R.drawable.icon; //. String tickertext = " "; //. long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickertext, when);. Notification number,

Chapter 09. 1,. notification.number++; Notification. number 0-1.. 1.. setlatest EventInfo. 2. UI. UI contentview. setlatesteventinfo. 9 4,,,.. PendingIntent.. 9 20 setlatesteventinfo. Context context = getapplicationcontext(); //.

431 String expandedtext = " "; // String expandedtitle = " "; //. Intent intent = new Intent(this, MyActivity.class); PendingIntent launchintent = PendingIntent.getActivity(context, 0, intent, 0); notification.setlatesteventinfo(context, expandedtitle, expandedtext, launchintent); ( SMS ). ( ) setlatesteventinfo,... 9 5 9 21, 9 22, 9 23. 9 21,,. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dp" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/status_icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignparentleft="true" />

Chapter 09 <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingleft="10px" android:layout_torightof="@id/status_icon"> <TextView android:id="@+id/status_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:textcolor="#000" android:textsize="14sp" android:textstyle="bold" /> <ProgressBar android:id="@+id/status_progress" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/status_text" android:progressdrawable="@android:drawable/progress_horizontal" android:indeterminate="false" android:indeterminateonly="false" /> </RelativeLayout> </RelativeLayout> RemoteView contentview. contentintent. 9 22 ongoing Notification. Notification notification = new Notification(R.drawable.icon, " ", System.currentTimeMillis()); notification.flags = notification.flags Notification.FLAG_ONGOING_EVENT; notification.contentview = new RemoteViews(this.getPackageName(), R.layout.my_status_window_layout); Intent intent = new Intent(this, MyActivity.class); PendingIntent pendingintent = PendingIntent.getActivity(this, 0, intent, 0); notification.contentintent = pendingintent;

433 contentview contentintent, 9 23 set*. 9 23 9 21. notification.contentview.setimageviewresource(r.id.status_icon, R.drawable.icon); notification.contentview.settextviewtext(r.id.status_text, " :"); notification.contentview.setprogressbar(r.id.status_progress, 100, 50, false);.. 9 24 ID NotificationManager notify. int notificationref = 1; notificationmanager.notify(notificationref, notification);, ID NotificationManager notify. notify Notification. ID Notification

Chapter 09. ID. ID NotificationManager cancel. notificationmanager.cancel(notificationref);,. EarthquakeService.,. Earthquake. 1. EarthquakeService Notification. Notification. private Notification newearthquakenotification; public static final int NOTIFICATION_ID = 1; 2. oncreate Notification. public void oncreate() { updatetimer = new Timer("earthquakeUpdates"); int icon = R.drawable.icon; String tickertext = " "; long when = System.currentTimeMillis(); newearthquakenotification= new Notification(icon, import import android.app.notification;

435 tickertext, when); 3. EarthquakeLookupTask. onprogressupdate. setlatesteventinfo.. protected void onprogressupdate(quake... values) { String svcname = Context.NOTIFICATION_SERVICE; NotificationManager notificationmanager = (NotificationManager)getSystemService(svcName); Context context = getapplicationcontext(); String expandedtext = values[0].getdate().tostring(); String expandedtitle = "M:" + values[0].getmagnitude() + " " + values[0].getdetails(); Intent startactivityintent = new Intent(EarthquakeService.this, Earthquake.class); PendingIntent launchintent = PendingIntent.getActivity(context, 0, startactivityintent, 0); newearthquakenotification.setlatesteventinfo(context, expandedtitle, expandedtext, launchintent); newearthquakenotification.when = java.lang.system.currenttimemillis(); notificationmanager.notify(notification_id, newearthquakenotification); Toast.makeText(context, expandedtitle, Toast.LENGTH_SHORT).show(); import import android.app.notificationmanager; import android.app.pendingintent; import android.widget.toast;

Chapter 09 4. Earthquake EarthquakeMap.. 4.1. Earthquake. oncreate. NotificationManager notificationmanager; public void oncreate(bundle savedinstancestate) { [... oncreate... ] String svcname = Context.NOTIFICATION_SERVICE; notificationmanager = (NotificationManager)getSystemService(svcName); 4.2. EarthquakeReceiver onreceive.., onreceive. onreceive. public void onreceive(context context, Intent intent) { loadquakesfromprovider(); notificationmanager.cancel(earthquakeservice.notification_id); 4.3. onresume. public void onresume() { notificationmanager.cancel(earthquakeservice.notification_id); import import android.app.notificationmanager;

437 IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); super.onresume(); 4.4. Earthquake EarthquakeMap. NotificationManager notificationmanager; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.earthquake_map); ContentResolver cr = getcontentresolver(); earthquakecursor = cr.query(earthquakeprovider.content_uri, null, null, null, null); MapView earthquakemap = (MapView)findViewById(R.id.map_view); earthquakemap.getoverlays().add(new EarthquakeOverlay(earthquakeCursor)); String svcname = Context.NOTIFICATION_SERVICE; notificationmanager = (NotificationManager)getSystemService(svcName); public void onresume() { notificationmanager.cancel(earthquakeservice.notification_id); earthquakecursor.requery(); IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); import import android.app.notificationmanager;

Chapter 09 super.onresume(); public class EarthquakeReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { notificationmanager.cancel(earthquakeservice.notification_id); earthquakecursor.requery(); MapView earthquakemap = (MapView)findViewById(R.id.map_view); earthquakemap.invalidate();.,,....,,. Notification defaults. Notification.DEFAULT_LIGHTS Notification.DEFAULT_SOUND

439 Notification.DEFAULT_VIBRATE Notification. notification.defaults = Notification.DEFAULT_SOUND Notification.DEFAULT_VIBRATE; Notification.DEFAULT_ALL.... URI sound. notification.sound = ringuri;. 11. announcenewquake, 6. if (quake.getmagnitude() > 6) { Uri ringuri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); newearthquakenotification.sound = ringuri; vibration pattern,

Chapter 09.. long Notification vibrate.... uses-permission. <uses-permission android:name="android.permission.vibrate"/>. 1, 5. long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 ; notification.vibrate = vibrate;. announcenewquake.. exponential scale. 1 1. 10, 20. Richter scale 3 7 200 4. double vibratelength = 100*Math.exp(0.53*quake.getMagnitude()); long[] vibrate = new long[] {100, 100, (long)vibratelength ; newearthquakenotification.vibrate = vibrate;

441 Notification LED. ledargb LED, ledoffms ledonms LED. ledonms 1, ledoffms 0 LED, 0 LED. LED Notification flags FLAG_SHOW_ LIGHTS. LED. notification.ledargb = Color.RED; notification.ledoffms = 0; notification.ledonms = 1; notification.flags = notification.flags Notification.FLAG_SHOW_LIGHTS;., LED. LED,. int color; if (quake.getmagnitude() < 5.4) color = Color.GREEN; else if (quake.getmagnitude() < 6) color = Color.YELLOW; else color = Color.RED;

Chapter 09 newearthquakenotification.ledargb = color; newearthquakenotification.ledoffms = (int)vibratelength; newearthquakenotification.ledonms = (int)vibratelength; newearthquakenotification.flags = newearthquakenotification.flags Notification.FLAG_SHOW_LIGHTS; Notification FLAG_ONGOING_EVENT ongoing notifications, FLAG_INSISTENT insistent notifications... notification.flags = notification.flags Notification.FLAG_ONGOING_EVENT; 9 6. (,, ).

443.. notification.flags = notification.flags Notification.FLAG_INSISTENT;....,,..,.,,. Handler,..

Chapter 09 AlarmManager. AlarmManager getsystemservice. AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); one shot Alarm set,,. (, ).. set. RTC_WAKEUP. RTC. ELAPSED_REALTIME... ELAPSED_REALTIME_WAKEUP. 9 25. int alarmtype = AlarmManager.ELAPSED_REALTIME_WAKEUP; long timeorlengthofwait = 10000; String ALARM_ACTION = "ALARM_ACTION"; Intent intenttofire = new Intent(ALARM_ACTION); PendingIntent pendingintent = PendingIntent.getBroadcast(this, 0, intenttofire, 0); alarms.set(alarmtype, timeorlengthofwait, pendingintent); RTC ELAPSED_REALTIME

445.. cancel. alarms.cancel(pendingintent); 9 26.,. 30,. AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); String MY_RTC_ALARM = "MY_RTC_ALARM"; String ALARM_ACTION = "MY_ELAPSED_ALARM"; PendingIntent rtcintent = PendingIntent.getBroadcast(this, 0, new Intent(MY_RTC_ALARM), 1); PendingIntent elapsedintent = PendingIntent.getBroadcast(this, 0, new Intent(ALARM_ACTION), 1); // 5. Date t = new Date(); t.settime(java.lang.system.currenttimemillis() + 60*1000*5); alarms.set(alarmmanager.rtc_wakeup, t.gettime(), rtcintent); // 30. alarms.set(alarmmanager.elapsed_realtime, 30*60*1000, elapsedintent); //. alarms.cancel(rtcintent);

Chapter 09.,.. 9 27 setrepeating setinexactrepeating.,,. setrepeating.. setinexactrepeating. AlarmManager. INTERVAL_FIFTEEN_MINUTES INTERVAL_HALF_HOUR INTERVAL_HOUR INTERVAL_HALF_DAY INTERVAL_DAY inexact repeating alarms... //,. alarms.setrepeating(alarmmanager.elapsed_realtime_wakeup,

447 60*60*1000, 60*60*1000, elapsedintent); //. alarms.setinexactrepeating(alarmmanager.elapsed_realtime_wakeup, 60*60*1000, AlarmManager.INTERVAL_DAY, elapsedintent);.. 1. BroadcastReceiver EarthquakeAlarmReceiver. package com.paad.earthquake; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; public class EarthquakeAlarmReceiver extends BroadcastReceiver { 2. onreceive EarthquakeService. public void onreceive(context context, Intent intent) { Intent startintent = new Intent(context, EarthquakeService.class); context.startservice(startintent);

Chapter 09 3. public static. public static final String ACTION_REFRESH_EARTHQUAKE_ALARM = "com.paad.earthquake.action_refresh_earthquake_alarm"; 4. EarthquakeAlarmReceiver, 3 <intent-filter>. <receiver android:name=".earthquakealarmreceiver"> <intent-filter> <action android:name="com.paad.earthquake.action_refresh_earthquake_alarm" /> </intent-filter> </receiver> 5. EarthquakeService oncreate AlarmManager, PendingIntent. timertask. AlarmManager alarms; PendingIntent alarmintent; public void oncreate() { int icon = R.drawable.icon; String tickertext = "New Earthquake Detected"; long when = System.currentTimeMillis(); newearthquakenotification = new Notification(icon, tickertext, when); alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); String ALARM_ACTION; ALARM_ACTION = EarthquakeAlarmReceiver.ACTION_REFRESH_EARTHQUAKE_ALARM; Intent intenttofire = new Intent(ALARM_ACTION); import import android.app.alarmmanager;

449 alarmintent = PendingIntent.getBroadcast(this, 0, intenttofire, 0); 6. onstartcommand.. Service.START_STICKY Service.START_NOT_STICKY. 7... public int onstartcommand(intent intent, int flags, int startid) { //. Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int minmagindex = prefs.getint(preferences.pref_min_mag, 0); if (minmagindex < 0) minmagindex = 0; int freqindex = prefs.getint(preferences.pref_update_freq, 0); if (freqindex < 0) freqindex = 0; boolean autoupdate = prefs.getboolean(preferences.pref_auto_update, false); Resources r = getresources(); int[] minmagvalues = r.getintarray(r.array.magnitude); int[] freqvalues = r.getintarray(r.array.update_freq_values); minimummagnitude = minmagvalues[minmagindex]; int updatefreq = freqvalues[freqindex]; import import android.os.systemclock;

Chapter 09 if (autoupdate) { int alarmtype = AlarmManager.ELAPSED_REALTIME_WAKEUP; long timetorefresh = SystemClock.elapsedRealtime() + updatefreq*60*1000; alarms.setrepeating(alarmtype, timetorefresh, updatefreq*60*1000, alarmintent); else alarms.cancel(alarmintent); refreshearthquakes(); ; return Service.START_NOT_STICKY; 7. EarthquakeLookupTask onpostexecute stopself. protected void onpostexecute(void result) { stopself(); 8. updatetimer TimerTask dorefresh....... LED.

451... AsyncTask GUI 10..,.