View
245
Download
5
Category
Preview:
Citation preview
8. Notification 과 Alarm
Unlocking Android
토스트 메시지 ( 알림 창 )
2
문자 메시지가 도착했을 때 사용자에게 도착한 메시지의
내용과 함께 메시지 수신 사실을 알려주기 위해 간단한
메시지를 팝업 시켜주는 토스트 다이얼로그를 사용함 .
토스트 (Toast) : 사용자에게 이벤트가 발생했음을
알려주도록 디자인된 한시적인 메시지
Unlocking Android
AndroidManifest.xml
3
<?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 이름으로 리시버
동작
<intent-filter>
<action android:name=“android.provider.Telephony.SMS_RECEIVED”/>
</intent-filter>
</receiver>
</application>
</manifest>
SMS 메시지 수신을 위한 퍼미션 설정
Unlocking Android
SMSNotifyExample
4
public class SMSNotyfyExampleActivity extends
Activirty {
@override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
}
Unlocking Android
SMS 인텐트리시버
5
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)
6
사용자가 메시지를 없애기 전까지 계속해서 해당 내용을 보여줌
Notification 클래스
접근 타입 메서드 내용
pub-lic
int ledARGB 알람을 위한 LED 의 색상
pub-lic
int ledOffMS LED 가 깜박일 때 꺼지는 속도
pub-lic
int ledOnMS LED 가 깜박일 때 켜지는 속도
pub-lic
ContentURI Sound 실행될 사운드
pub-lic
Remove-Views
ContentView 상태 바에서 StatusBarlcon 이 선택되었을 때 표시해줄 뷰
pub-lic
CharSe-quence
statusBar-BalloonText
상태 바에서 StatusBarlcon 이 선택되었을 때 표시해줄 텍스트
pub-lic
PendingIn-tent
ContentIntent 아이콘이 클릭되었을 때 실행할 인텐트
pub-lic
int Icon 상태바에서 아이콘으로 사용될 수 있는 리소스 id
pub-lic
CharSe-quence
ticketText 아이템이 상태 바에 추가되었을 때 보이는 텍스트
pub-lic
Long[] Vibrate 진동이 울리는 패턴
Unlocking Android
노티피케이션 (2/2)
7
노티피케이션을 사용하려면 …
Notification notif = new Notification (
context, // 애플리케이션 컨텍스트
icon, // 상태 바에 나타날 아이콘
ticketText, // 티커에 보여줄 텍스트
when, // 노티피케이션 발생 시간
Title, // 노티피케이션 타이틀
TextBody, // 노티피케이션의 내용
contextIntent, // 콘텐트인텐트
appIntent); // 애플리케이션 인텐트
노티피케이션 메시지를 보내려면 …
nm.notify(String, Notification); // nm 은 Notification
Manager 를 의미
Unlocking Android
SMSNotifyActivity
8
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)
9
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)
10
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)
11
알람을 이용하여 사용자가 지정한 임의의 시점에 애플리케이션이
실행되도록 스케쥴링이 가능
지정된 어떤 일을 보다 세련된 방법으로 사용자에게 알려줌으로써
다양한 애플리케이션에서 사용될 수 있음
알람 기능은 알람을 인텐트와 함께 등록시켜줌으로써 동작되는데
정해진 시간이 되면 인텐트를 브로드캐스팅 함 ( 단말기가
슬립모드인 경우에도 자동으로 수행됨 )
Context.getSystemService(context.ALARM_SERVICE);
Unlocking Android
알 람 (2/2)
12
AlarmManager 의 메서드
Return 타입 메서드와 설명
voidcancel(PendingIntent intent)
일치하는 인텐트 알람 제거
voidset(int type, long triggerAtTime, PendingIntent op-
eration)
알람 설정
voidsetRepeating(int type, long triggerAtTime, long in-terval, PendingIntent operation)반복 알람 설정
voidSetTimeZone(String TimeZone)
알람을 위한 시간대 설정
Unlocking Android
AndroidManifest.xml
13
<?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
14
<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
15
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
16
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_REALTIMESystemClock.elapsedRealtime 메서드의 알람 시간
(Sleep 모드 시간을 포함한 부팅 이후의 시간 )
ELAPSED_REALTIME_WAK
EUP
SystemClock.elapsedRealtime 메서드의 알람 시간
(Sleep 모드 시간을 포함한 부팅 이후의 시간 ), 알람이
울리면 기기를 작동
RTC System.currentTimeMillis 메서드의 알람 시간
RTC_WAKEUPSystem.currentTimeMillis 메서드의 알람 시간 , 알람이
울리면 기기를 작동
Unlocking Android
SetAlarm.java (1/2)
18
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)
19
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);
}
};
}
Recommended