도래울

[Android] Notification 본문

개발/Android

[Android] Notification

도래울 2016. 2. 5. 13:15

어플리케이션에서 어떠한 특정 이벤트가 발생하여 사용자에게 알려야 할 상황에서 활용한다.

예) 문자…….등등

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//일단  아래의 두가지의 객체가 필요하다.
  
NotificationManager mNM;  //(생성한 notification을 표시하기위해 이를 관리하는 NorificationManager)
Context con;   //(어플리케이션/컴포넌트의 컨텍스트 객체)
  
public void notiShow(){
  
    mNM = (NotificationManager)con.getSystemService(Context.NOTIFICATION_SERVICE);
  
    CharSequence text1 ="Noti Test";
    CharSequence text2 = "Noti Test 입니다.";
  
    Notification notification = new Notification(R.drawable.noti_icon, // 표시할 아이콘
                                                 text1, // 표시할 텍스트
                                                 0 // 표시할 시각 , 0은 시간 안나옴
                                                 );
  
        /*
  
         추가 적으로 notification 에 flag를 줄수있다.
  
         예로 아래와 같이 하면 지우기 버튼을 눌러도 지워지지않는다.
  
         notification.flags = notification.FLAG_NO_CLEAR;
  
         */
  
    PendingIntent contentIntent = PendingIntent.getActivity(con, 0, new Intent(con, Main.class), 0);
  
        /*
  
        다른 컴포넌트를 호출할 때 인텐트(Intent) 대신 PendingIntent를 사용한다.
  
        인텐트가 어떤 작업을 할 지 그 "내용"만 담고 있는 것에 반해,
  
        PendingIntent는 객체 초기화 과정에서 호출할 컴포넌트를 지정하게 되는데
  
        위 코드는 액티비티를 호출하는 PendingIntent를 초기화하는 코드다.
  
        파라메타는 어플리케이션/컴포넌트의 컨택스트 객체, 요청코드, 인탠트 객체, 옵션 이다
  
         */
  
    notification.setLatestEventInfo(con, text1, text2, contentIntent);
  
    // 생성한 Notification을 표시하기위해 setLatestEventInfo()메소드를 사용한다.
  
    mNM.notify(0, notification);
  
    //0이라는 고유의 아이디를 갖는 notification을 표시한다. 고유 아이디 0 은 해제할때 쓴다.
    //해제는 mNM.cancel(0); 혹은 mNM.cancelALL();
  
}


Comments