8. Notification과 Alarm.

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 6 Overview Programming Tutorial 3: Sending/Receiving SMS Messages.
Advertisements

Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
CSS216 MOBILE PROGRAMMING Android, Chapter 9 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
Cosc 4755 Android Notifications. There are a couple of ways to notify users with interrupting what they are doing The first is Toast, use the factory.
BroadcastReceiver.  Base class for components that receive and react to events  Events are represented as Intent objects  Intents received as parameter.
Notifications & Alarms.  Notifications  Alarms.
Cosc 4730 Android Dialogs and notifications. Notifications There are a couple of ways to notify users without interrupting what they are doing The first.
1 Working with the Android Services Nilanjan Banerjee Mobile Systems Programming University of Arkansas Fayetteville, AR
Cosc 5/4730 Android SMS. A note first Depending on the API level, an import changes because of a deprecated API 3 uses – import android.telephony.gsm.SmsManager;
@2011 Mihail L. Sichitiu1 Android Introduction Communication between Activities.
System broadcasts and services. System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE.
Cosc 5/4730 Android SMS and MMS.
SMS Read received SMS Read sent SMS Send SMS New app, SMSFun Button – Text: Send SMS – Id: sendSMSButton Permissions – send_sms – read_sms – receive_sms.
SMS. Short Message Service – Primarily text messages between mobile phones – First one sent December 3, 1982 “Merry Christmas” – In 2008 Approximately.
@2011 Mihail L. Sichitiu1 Android Introduction Hello Views Part 1.
Getting Started with Android APIs Ivan Wong. Motivation - “Datasheet” - Recently exposed to what’s available in Android - So let’s see what API’s are.
Developing Push Notifications (C2DM) for Android Vijai Co-Founder Adhish Technologies, Sweet’N’Spicy apps.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Broadcast Receiver Android Club Agenda Broadcast Receiver Widget.
Android Activities 1. What are Android Activities? Activities are like windows in an Android application An application can have any number of activities.
Homescreen Widgets Demystified Pearl AndroidTO // Oct 26, 2010.
Mobile Programming Lecture 6
로봇 모니터링 2/2 UNIT 21 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Broadcasting Service 2.
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.
로봇 전화번호부 4/4 UNIT 12 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 뷰 홀더 패턴을 사용할 수 있다. 토스트를 사용할 수 있다. 클릭 이벤트를 처리할 수 있다. 2.
Android Programming-Activity Lecture 4. Activity Inside java folder Public class MainActivity extends ActionBarActivity(Ctrl + Click will give you the.
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.
Android - Broadcast Receivers
Robolectric (version 2.4 기준 ). class AbcTest public static void setUpOnce() { public void public void testA()
User notification Android Club Agenda Toast Custom Toast Notification Dialog.
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
Activity 생명주기 UNIT 13 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Logcat 액티비티 생명주기를 설명할 수 있다. 현재 상태를 저장할 수 있다. 2.
Notifications. A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification,
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
CHAP 11. 액티비티와 인텐트.
로봇을 조종하자 4/4 UNIT 18 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Intent Activity 호출 2.
목차 한국기술교육대학교 강사: 김 영 준 ㈜헬로앱스 1일차 아두이노 제어 실습
Android and s Ken Nguyen Clayton state University 2012.
아주대학교 LifecareScienceLAB Android Seminar 3 rd class Android Software Development 2011/05/04 – p.m. 06:00 – 팔달관 409 호 아주대학교.
Android Alert Dialog. Alert Dialog Place Button to open the dialog. public class MainActivity extends ActionBarActivity { private static Button button_sbm;
CHAP 7. 메뉴와 대화상자. © 2012 생능출판사 All rights reserved 메뉴의 종류 옵션 메뉴 : 사용자가 MENU 키를 누를 때 나타난다. 컨텍스트 메뉴 : 컨텍스트 메뉴는 사용자가 화면을 일정 시간 이상으로 길게 누르면 나타나는 메뉴이다.
Speech Service & client(Activity) 오지영.
Android 基本 I/O. 基本 I/O 介面元件 在此節中主要介紹常見的 I/O 使用者介 面元件 – Button, TextView, 以及 EditText , 學習者可以學會: – Android 的視窗表單設計 res/layout/main.xml – Android SDK –
Mobile Software Development for Android - I397 IT COLLEGE, ANDRES KÄVER, WEB:
David Sutton SMS TELEPHONY IN ANDROID. OUTLINE  This week’s exercise, an SMS Pub Quiz  Simulating telephony on an emulator  Broadcast Intents and broadcast.
Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
Mobile Software Development for Android - I397
Android N Amanquah.
CS499 – Mobile Application Development
Broadcast receivers.
GUI Programming Fundamentals
Android Notifications
Communication between Activities
S.RENUKADEVI/AP/SCD/ANDROID - AlarmManager
Android Widgets 1 7 August 2018
Android Introduction Hello Views Part 1.
Android – Read/Write to External Storage
Mobile Software Development for Android - I397
Developing Android Services
CIS 470 Mobile App Development
Android Notifications (Part 1)
Android Notifications (Part 2) Plus Alarms and BroadcastReceivers
UNIT 08 그림책 만들기 2/2 로봇 SW 콘텐츠 교육원 조용수.
CIS 470 Mobile App Development
Android Notifications
Android Developer Fundamentals V2 Lesson 5
ארועים ומאזינים android.
Notifying from the Background
Mobile Programming Broadcast Receivers.
Presentation transcript:

8. Notification과 Alarm

토스트 메시지(알림 창) 문자 메시지가 도착했을 때 사용자에게 도착한 메시지의 내용과 함께 메시지 수신 사실을 알려주기 위해 간단한 메시지를 팝업 시켜주는 토스트 다이얼로그를 사용함. 토스트(Toast) : 사용자에게 이벤트가 발생했음을 알려주도록 디자인된 한시적인 메시지 Unlocking Android

AndroidManifest.xml <?xml version=“1.0” encoding=“utf-8”?> <manifest xmlns:android=http://schemas.android.com/apk/res/android package=“com.msi.manning.chapter8”> <uses-permission android:name=“android.permission.RECEIVE_SMS”/> <application android:icon=“@drawable/chat”> // 인텐트필터를 가지고 리시버와 SMSNotify 정의 <activity android:name=“.SMSNotifyActivity” android:label=“@string/app_name”> <intent-filter> <action android:name=“android.intent.action.MAIN”/> <category android:name=“android.intent.category.LAUNCHER”/> </intent-filter> </activity> <receiver android:name”.SMSNotifyExample”> // SMSNotifyExample 이름으로 리시버 동작 <action android:name=“android.provider.Telephony.SMS_RECEIVED”/> </receiver> </application> </manifest> SMS 메시지 수신을 위한 퍼미션 설정 Unlocking Android

SMSNotifyExample public class SMSNotyfyExampleActivity extends Activirty { @override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } Unlocking Android

SMS 인텐트리시버 public class SMSNotifyExample extends BroadcastReceiver { private static final String LOG_TAG = “SMSReceiver”; public static final int NOTIFICATION_ID_RECEIVED = 0x1221; static final String Action = “android.provider.Telephony.SMS_RECEIVED; public void onReceiveIntent(Context context, Intent intent) { if (intent.getAction().equals(SMSNotifyExample.ACTION) { StringBuilder sb = new StringBuilder(); Bundle bundle = intent.getExtras(); if (bundle != null) { Object [] pdusObj = (Object []) bundle.get(“pdus”); SmsMessage [] messages = new SmsMessage[pdusObj.length]; for (SmsMessage currentMessage : messages) { sb.append(“Received SMS\nFrom: “); sb.append(currentMessage.getDisplayOriginatingAddress()); sb.append(“\n----Message----\n”); sb.append(currentMessage.getDisplayMessageBody()); } Log.i(SMSNotifyExample.LOG_TAG, “[SMSApp] onReceiveIntent: “ + sb); Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show(); } } @Override public void onReceive(Context context, Intent intent) { 인텐트를 수신할 수 있도록 브로드캐스트 리시버 확장 SMS 수신 시 안드로이드에 의해 액션 실행 SMS 메시지가 도착했다는 것과 다불어 발신자, 내용을 보여줄 메서드 생성 토스트를 이용해서 간단한 메시지를 담은 팝업 다이얼로그를 사용자에게 보여줌 Unlocking Android

노티피케이션 (1/2) 사용자가 메시지를 없애기 전까지 계속해서 해당 내용을 보여줌 Notification 클래스 접근 타입 메서드 내용 public int ledARGB 알람을 위한 LED의 색상 ledOffMS LED가 깜박일 때 꺼지는 속도 ledOnMS LED가 깜박일 때 켜지는 속도 ContentURI Sound 실행될 사운드 RemoveViews ContentView 상태 바에서 StatusBarlcon이 선택되었을 때 표시해줄 뷰 CharSequence statusBarBalloonText 상태 바에서 StatusBarlcon이 선택되었을 때 표시해줄 텍스트 PendingIntent ContentIntent 아이콘이 클릭되었을 때 실행할 인텐트 Icon 상태바에서 아이콘으로 사용될 수 있는 리소스 id ticketText 아이템이 상태 바에 추가되었을 때 보이는 텍스트 Long[] Vibrate 진동이 울리는 패턴 Unlocking Android

노티피케이션 (2/2) 노티피케이션을 사용하려면 … Notification notif = new Notification ( context, // 애플리케이션 컨텍스트 icon, // 상태 바에 나타날 아이콘 ticketText, // 티커에 보여줄 텍스트 when, // 노티피케이션 발생 시간 Title, // 노티피케이션 타이틀 TextBody, // 노티피케이션의 내용 contextIntent, // 콘텐트인텐트 appIntent); // 애플리케이션 인텐트 노티피케이션 메시지를 보내려면 … nm.notify(String, Notification); // nm은 Notification Manager를 의미 Unlocking Android

SMSNotifyActivity public class SMSNotifyActivity extends Activity { public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.cancle(R.string.app_name); } 노티피케이션 매니저를 사용하여 노티피케이션을 검색 cancel 메서드를 사용하여 실행을 취소 Unlocking Android

SMSNotifyExample.java 업데이트 (1/2) public class SMSNotifyExample extends BroadcastReceiver { private static final String LOG_TAG = “SMSReceiver”; public static final int NOTIFICATION_ID_RECEIVED = 0x1221; static final String Action = “android.provider.Telephony.SMS_RECEIVED; private CharSequence tickerMessage = null; public void onReceiveIntent(Context context, Intent intent) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (intent.getAction().equals(SMSNotifyExample.ACTION) { StringBuilder sb = new StringBuilder(); Bundle bundle = intent.getExtras(); if (bundle != null) { Object [] pdusObj = (Object []) bundle.get(“pdus”); SmsMessage [] messages = new SmsMessage[pdusObj.length]; for (SmsMessage currentMessage : messages) { sb.append(“Received SMS\nFrom: “); sb.append(currentMessage.getDisplayOriginatingAddress()); sb.append(“\n----Message----\n”); sb.append(currentMessage.getDisplayMessageBody()); } 노티피케이션을 표시하는 상태 바에서 스크롤이 필요한 메시지들을 포함하는 티커 메시지 추가 Unlocking Android

SMSNotifyExample.java 업데이트 (2/2) Log.i(SMSNotifyExample.LOG_TAG, “[SMSApp] onReceiveIntent: “ + sb); abortBroadcast(); Intent i = new Intent(context, SMSNotifyActivity.class); context.startActivity(i); CharSequence appName = “SMSNotifyExample”; this.tickerMessage = sb.toString(); Long theWhen = System.currentTimeMillis(); PendingIntent.getBroadcast((Context) appName, 0, i, 0); Notification notif = new notification(R.drawable.incoming, this.tickerMessage, theWhen); notif.vibrate = new long [] {100, 250, 100, 500}; nm.notify(R.string.alert_message, notif); } @Override public void onReceive(Context context, Intent intent) { 노티피케이션 생성 티커에서 보여줄 텍스트 상태 바를 위한 아이콘 설정 노티피케이션 브로드캐스팅 Unlocking Android

알 람 (1/2) 알람을 이용하여 사용자가 지정한 임의의 시점에 애플리케이션이 실행되도록 스케쥴링이 가능 알 람 (1/2) 알람을 이용하여 사용자가 지정한 임의의 시점에 애플리케이션이 실행되도록 스케쥴링이 가능 지정된 어떤 일을 보다 세련된 방법으로 사용자에게 알려줌으로써 다양한 애플리케이션에서 사용될 수 있음 알람 기능은 알람을 인텐트와 함께 등록시켜줌으로써 동작되는데 정해진 시간이 되면 인텐트를 브로드캐스팅 함(단말기가 슬립모드인 경우에도 자동으로 수행됨) Context.getSystemService(context.ALARM_SERVICE); Unlocking Android

알 람 (2/2) AlarmManager의 메서드 Return 타입 메서드와 설명 void 알 람 (2/2) AlarmManager의 메서드 Return 타입 메서드와 설명 void cancel(PendingIntent intent) 일치하는 인텐트 알람 제거 set(int type, long triggerAtTime, PendingIntent operation) 알람 설정 setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) 반복 알람 설정 SetTimeZone(String TimeZone) 알람을 위한 시간대 설정 Unlocking Android

AndroidManifest.xml <?xml version=“1.0” encoding=“utf-8”?> <manifest xmlns:android=http://schemas.android.com/apk/res/android package=“com.msi.manning.chapter8.simpleAlarm”> <application android:icon=“@drawable/clock”> <activity android:name=“.GenerateAlarm” android:label=“@string/app_name”> <intent-filter> <action android:name=“android.intent.action.MAIN”/> <category android:name=“android.intent.category.LAUNCHER”/> </intent-filter> </activity> <receiver android:name”.AlarmReceiver” android:process=“ :remote” /> </application> </manifest> SMS 메시지 수신을 위한 퍼미션 설정 Unlocking Android

string.xml과 main.xml <string name=“set_alarm_text”>Set Alarm</string> <string name=“alarm_message”>Alarm Fired</string> <Button android:id=“@+id/set_alarm_button” android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“@string/set_alarm_text”> <requestFocus /> </Button> Unlocking Android

AlarmReceiver.java public class AlarmReceiver extends BroadcastReceiver { public void onReceiveIntent(Context context, Intent intent) { Toast,makeText(context, R.string.app_name, Toast.LENGTH_SHORT).show(); } @Override public voic onReceive(Context context, Intent intent { onReceiveIntent 메서드 생성 인텐트 수신 시 토스트 브로드캐스팅 Unlocking Android

simpleAlarm.java Unlocking Android public class GenerateAlarm extends Activity { Toast mToast; @override protected void onCreate (Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.set_alarm_button); button.setOnClickListener(this.mOneShotListener); } private OnClickListener mOneShotListener = new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(GenerateAlarm.this, AlarmReceiver.class); PendingIntent appIntent = PendingIntent.getBroadcast(GenerateAlarm.this, 0, intent, 0); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 30); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), appIntent); if (GenerateAlarm.this.mToast != null) { GenerateAlarm.this.mToast.cancel(); GenerateAlarm.this.mToast = Toast.makeText(GenerateAlarm.this, R.string.alarm_message, Toast.LENGTH+LONG); GenerateAlarm.this.mToast.show(); }; mOneShotListener를 호출하는 버튼 생성하여 알람을 시작하게 함 실제 알람이 발생했을 때 실행될 인텐트 생성 알람이 울릴 시간 설정 알람 매니저 생성 알람 설정 Unlocking Android

ELAPSED_REALTIME_WAKEUP 알람 매니저의 알람 타입들 타 입 설 명 ELAPSED_REALTIME SystemClock.elapsedRealtime 메서드의 알람 시간(Sleep 모드 시간을 포함한 부팅 이후의 시간) ELAPSED_REALTIME_WAKEUP SystemClock.elapsedRealtime 메서드의 알람 시간(Sleep 모드 시간을 포함한 부팅 이후의 시간), 알람이 울리면 기기를 작동 RTC System.currentTimeMillis 메서드의 알람 시간 RTC_WAKEUP System.currentTimeMillis 메서드의 알람 시간, 알람이 울리면 기기를 작동 Unlocking Android

SetAlarm.java (1/2) public class SetAlarm extends Activity { private NotificationManager nm; Toast mToast; @override protected void onCreate (Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); this.nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Button button = (Button) findViewById(R.id.set_alarm_button); button.setOnClickListener(this.mOneShotListener); } private void showNotification(int statusBarIconId, int statusBarTextId, int detailedTextId, boolean showIconOnly) { Intent contentIntent = new Intent(this, SetAlarm.class); PendingIntent theappIntent = PendingIntent.getBroadcast(SetAlarm.this, 0, contentIntent, 0); CharSequence from = “Alarm Manager”; CharSequence message = “The Alarm was fired”; String tickerText = chowIconOnly ? null : this.getString(statusBarTextID); Notification notif = new Notification(statusBarIconID, tickerText, System.currentTimeMillis()); notif.setLatestEventInfo(this, from, message, theappIntent); this.nm.notify(this.YOURAPP_NOTIFICATION_ID, notif); Unlocking Android

SetAlarm.java (2/2) private OnClickListener mOneShotListener = new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(SetAlarm.this, AlarmReceiver.class); PendingIntent appIntent = PendingIntent.getBroadcast(SetAlarm.this, 0, intent, 0); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 30); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), appIntent); showNotification(R.drawable.alarm, R.string.alarm_message, R.string.alarm_message, false); } }; Unlocking Android