Presentation is loading. Please wait.

Presentation is loading. Please wait.

8. Notification과 Alarm.

Similar presentations


Presentation on theme: "8. Notification과 Alarm."— Presentation transcript:

1 8. Notification과 Alarm

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

3 AndroidManifest.xml <?xml version=“1.0” encoding=“utf-8”?>
<manifest xmlns:android= package=“com.msi.manning.chapter8”> <uses-permission android:name=“android.permission.RECEIVE_SMS”/> <application // 인텐트필터를 가지고 리시버와 SMSNotify 정의 <activity android:name=“.SMSNotifyActivity” <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

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

5 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

6 노티피케이션 (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

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

8 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

9 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

10 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

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

12 알 람 (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

13 AndroidManifest.xml <?xml version=“1.0” encoding=“utf-8”?>
<manifest xmlns:android= package=“com.msi.manning.chapter8.simpleAlarm”> <application <activity android:name=“.GenerateAlarm” <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

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

15 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

16 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

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

18 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

19 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


Download ppt "8. Notification과 Alarm."

Similar presentations


Ads by Google