태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

티스토리 툴바



이 게시물을 무단으로 사용하는 행위(비영리, 영리 포함)는 CCL 2.0 저작자 표시-비영리-변경금지 라이센스에 의거하여 금지되어 있습니다. 원본 글의 출처 및 저작자를 표시해 주신다면 글의 스크랩은 자유롭게 하실 수 있습니다. 단, 비영리 목적의 발표(스터디 등)에 위 글을 사용하고 싶으신 분은 제게 미리 메일로 문의 부탁드립니다.

저작권과 관련된 자세한 사항은 이곳을 참조해 주시기 바랍니다.


강좌 작성환경
SDK Version : Android SDK 2.1, release 1
ADT Version : 0.9.5

추후 SDK업데이트로 인해 글의 내용과 최신 SDK 내용간 차이가 있을 수 있습니다.

Notification에 대해 간략하게 알아보았으니, 실제로 Notification을 만들어보도록 하겠습니다.

[어플리케이션 정보]

액티비티
  • NotificationBuilder (NotificationBuilder.java)
  • NotificationMessage (NotificationMessage.java)

레이아웃
  • main.xml (NotificationBuilder)

권한 (uses-permission)
  • 사용하지 않음

외부 라이브러리 (uses-library)
  • 사용하지 않음

API Level
  • 7 :  Android 2.1

어플리케이션 소스:
예제로 만들어 볼 어플리케이션에서는 우리가 원하는 문구로 Notification을 생성할 수 있도록 상태 표시줄에 표시되는 텍스트 및 Notification 리스트에 표시되는 문구를 입력받을 수 있도록 되어있습니다.



원하는 문구를 입력한 후 버튼을 누르면 Notification이 Notification Manager에 등록되게 되며, 예제 어플리케이션에서는 등록하는 순간 바로 Notification이 나오도록 지정하여 Notification이 뜨는 것을 확인할 수 있습니다.


상태 표시줄에 메시지가 표시됩니다.

메시지가 표시된 후에는 아이콘이 표시되어 있습니다.



예제 어플리케이션의 동작은 다음과 같습니다.

1. Notification에 표시할 문구를 사용자로부터 입력받음
2. 입력받은 문구로 Notification 생성 및 등록
3. Notification이 상태 표시줄에 표시됨
4. Notification List에 표시된 Notification 항목을 클릭하면 NotificationMessage 액티비티가 실행되고, 표시되어있던 Notification이 사라짐

우선, Notification을 생성하는 액티비티인 NotificationBuilder부터 만들어보도록 하겠습니다.

[NotificationBuilder.java]
package com.androidhuman.example.NotificationBuilder;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class NotificationBuilder extends Activity implements OnClickListener{
    
	private EditText tickerText;
	private EditText contentTitle;
	private EditText contentText;
	private Button registerButton;
	private NotificationManager nm;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tickerText = (EditText)findViewById(R.id.tickerText);
        contentTitle = (EditText)findViewById(R.id.contentTitle);
        contentText = (EditText)findViewById(R.id.contentText);
        registerButton = (Button)findViewById(R.id.registerNotification);
        
        registerButton.setOnClickListener(this);
    
    }

	public void onClick(View v) {
		
		switch(v.getId()){
		case R.id.registerNotification:
			// Get Notification Service
			nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
			
			PendingIntent intent = PendingIntent.getActivity(
					NotificationBuilder.this, 0, 
					new Intent(NotificationBuilder.this, NotificationMessage.class), 0);
			
			String ticker = tickerText.getText().toString();
			String title = contentTitle.getText().toString();
			String text = contentText.getText().toString();
										
			// Create Notification Object
			Notification notification =
				new Notification(android.R.drawable.ic_input_add,
						ticker, System.currentTimeMillis());
			
			notification.setLatestEventInfo(NotificationBuilder.this, 
					title, text, intent);
			
			nm.notify(1234, notification);
			Toast.makeText(NotificationBuilder.this, "Notification Registered.", 
					Toast.LENGTH_SHORT).show();
		break;
		}
		
	}
	
}

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    style="?android:attr/listSeparatorTextViewStyle" 
    android:text="TickerText" android:layout_marginBottom="3dp"/>
    
<EditText android:layout_height="wrap_content" 
	android:id="@+id/tickerText" 
	android:hint="Ticker Text" 
	android:layout_width="fill_parent"></EditText>

<TextView android:layout_height="wrap_content" 
	android:text="Notification Panel" 
	android:layout_width="fill_parent" 
	style="?android:attr/listSeparatorTextViewStyle" 
	android:layout_marginBottom="3dp"></TextView>

<EditText android:layout_height="wrap_content" 
	android:layout_width="fill_parent" 
	android:id="@+id/contentTitle" 
	android:hint="Content TItle"></EditText>

<EditText android:layout_height="wrap_content" 
	android:id="@+id/contentText" 
	android:hint="Content Text" 
	android:layout_width="fill_parent"></EditText>

<Button android:layout_height="wrap_content" 
	android:text="Register Notification to Notification Manager" 
	android:id="@+id/registerNotification" 
	android:layout_width="fill_parent"></Button>
</LinearLayout>

Notification의 생성은 Notification 생성 버튼(registerButton)을 눌렀을 때 시작됩니다. 따라서 Notification 생성 코드는 버튼의 클릭 리스너인 OnClick() 메소드에서 처리합니다. 아래는 onClick 메소드 내부의 Notification 생성 부분입니다.

[NotificationBuilder.java]

// Get Notification Service
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
			
PendingIntent intent = PendingIntent.getActivity(
		NotificationBuilder.this, 0, 
		new Intent(NotificationBuilder.this, NotificationMessage.class), 0);
			
String ticker = tickerText.getText().toString();
String title = contentTitle.getText().toString();
String text = contentText.getText().toString();
										
// Create Notification Object
Notification notification =
	new Notification(android.R.drawable.ic_input_add,
			ticker, System.currentTimeMillis());
	
notification.setLatestEventInfo(NotificationBuilder.this, title, text, intent);
	
nm.notify(1234, notification);
Toast.makeText(NotificationBuilder.this, "Notification Registered.", Toast.LENGTH_SHORT).show();

이 부분이 실질적으로 Notification을 처리하는 코드입니다. 하나하나씩 보도록 하죠.


 nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

Notification을 등록하기 위해 NotificationManager 객체를 생성합니다.

PendingIntent intent = 
	PendingIntent.getActivity(NotificationBuilder.this, 0, new Intent(NotificationBuilder.this, NotificationMessage.class), 0);

여기에서는 Notification List에 표시되는 Notification 항목을 클릭하면 실행할 액티비티를 설정합니다. 여기에서는 NotificationMessage 액티비티를 지정해 주었습니다. PendngIntent는 나중에 Notification Panel에 표시된 항목을 클릭했을 때 액티비티를 호출하기 위해 필요합니다. 여기에서는 액티비티를 호출하기 위해 getActivity()를 사용하였지만, 서비스를 호출하거나 브로드캐스트 메시지를 보내는 것도 가능합니다. 

API
public static PendingIntent getActivity (Context context, int requestCode, Intent intent, int flags)

위의 속성들 (context, requestCode, intent, flags)를 갖는 액티비티를 호출하는 PendingIntent 객체를 생성합니다.

NotificationMessage 액티비티의 구현은 아래에서 보도록 하고, 다음 코드로 넘어가도록 하겠습니다.

String ticker = tickerText.getText().toString();
String title = contentTitle.getText().toString();
String text = contentText.getText().toString();
EditText 필드로부터 상태 표시줄에 표시될 텍스트인 ticker, Notification List에 표시될 제목 및 내용인 title 과 text를 받아옵니다.

// Create Notification Object
Notification notification = 
	new Notification(android.R.drawable.ic_input_add, ticker, System.currentTimeMillis());
Notification 객체를 생성합니다. 여기에서는 상태 표시줄에 표시될 아이콘, 텍스트 및 표시될 시각을 지정해줍니다. Notification이 표시될 시각에 System.currentTimeMillis() (현재 시간)을 넣어주므로 Notification이 Notification Manager에 등록되자 마자 상태 표시줄에 해당 Notification이 표시되게 됩니다.

notification.setLatestEventInfo(NotificationBuilder.this, title, text, intent);
Notification List에 표시될 항목을 설정합니다. 제목 및 내용, 클릭시 수행할 작업인 PendingIntent를 넣어줍니다.
위에서 지정한 Ticker Text 및 Notification List에 표시되는 제목 및 내용이 표시되는 위치는 아래와 같습니다.



nm.notify(1234, notification);

마지막으로, Notification Manager에 생성된 Notification을 등록합니다.
Notification 등록시에는 추후 Notification Manager를 통해 등록한 Notification 표시를 해제하기 위해 각 Notifiation의 고유 ID를 같이 등록해줍니다.

Notification을 생성하고 등록해주는 과정을 살펴보면 아래와 같습니다. 



다음은 Notification 항목을 클릭했을 때 표시되는 액티비티인 NotificationMessage의 코드입니다.

[NotificationMessage.java]
package com.androidhuman.example.NotificationBuilder;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.widget.TextView;

public class NotificationMessage extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    TextView tv = new TextView(this);
	    tv.setText("위의 Notification이 사라진 것을 확인하셨나요? :)");
	    setContentView(tv);
	    
	    NotificationManager nm = 
	    	(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	    
	    // Cancel Notification
	    nm.cancel(1234);
	}

}

이 액티비티가 표시되면, Notification Manager의 cancel() 메소드를 호출하여 방금 표시되어 있던 Notification을 해제하게 됩니다. NotificationBuilder 액티비티와 동일하게 NotificationManager 서비스를 받아온 후, cancel()메소드에 아까 등록했던 Notification의 ID를 같이 넘겨주게 되면 해당 Notification이 해제, 즉 상태 표시줄 및 Notification List에서 사라지게 됩니다.

상태 표시줄에서 Notification이 사라진 것을 확인할 수 있습니다.



저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License


안드로이드 정보, 강좌를 누구보다 빨리 접하고 싶으신가요?

그렇다면 이메일 구독 혹은  구글 리더에 피드 추가 를 통해 업데이트되는 최신 글들을 받아보실 수 있습니다. :)




TRACKBACK http://androidhuman.tistory.com/trackback/273 관련글 쓰기

댓글을 달아 주세요

  1. 생각+

    정리를 참 잘하시네요
    잘 보았습니다.

    2010/06/14 11:13 [ ADDR : EDIT/ DEL : REPLY ]
  2. 방문객

    역시나 참 쉽게 설명 잘하시는거 같아요 잘 봤습니다 ^^

    2010/07/23 21:50 [ ADDR : EDIT/ DEL : REPLY ]
  3. 게스트

    커니님 강의 잘 보고 있구요 질문 있는데요

    AndroidManifest.xml의
    <activity android:name="NotificationMessage"></activity>
    이것이 뭔가요?
    소스 붙여 넣기로 만들땐 저 줄이 생성 안됬었구요
    노티에 등록된 후 클릭을 하면 반응이 없었거든요
    저줄을 추가하니 NotificationMessage.class의 화면이 나타나네요

    2011/02/09 12:29 [ ADDR : EDIT/ DEL : REPLY ]
    • http://androidhuman.tistory.com/entry/%EB%A9%94%EB%8B%88%ED%8E%98%EC%8A%A4%ED%8A%B8-%ED%8C%8C%EC%9D%BC-%EB%84%88%EB%8A%94-%EB%88%84%EA%B5%AC%EB%83%90

      여기를 참고하세요~

      2011/02/09 12:35 [ ADDR : EDIT/ DEL ]
  4. 왕밤빵

    커니님 궁금한게 있는데요...
    Notification을 띄우고 클릭시에 다른 어플이 실행되도록 구현중인데요.
    알람과 실행되는 어플 이렇게 2개의 어플이 있을경우에요..
    실행된 다른 어플에서 cancel을 해줘야하는데 알람어플의 ID값을 실행된 어플에서 받아올 수 있을까요?ㅠㅠ
    그것때문에 알람이 클릭해도 사라지지 않아서 문의드립니다..ㅜ

    2011/10/07 11:40 [ ADDR : EDIT/ DEL : REPLY ]
    • Notification을 생성할 때 플래그를 설정해주면 됩니다.

      http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL

      를 참고하세요.

      2011/10/07 13:14 [ ADDR : EDIT/ DEL ]
  5. 포베

    안녕하세요~
    예제대로 잘 따라해 봤는데요^^
    해당 방법대로 실행하면 잘 돼긴하는데.. 상태바에 아이콘이 남더라구요.
    아이콘을 숨기거나 지우는 방법은 없을까요??

    2012/04/23 13:49 [ ADDR : EDIT/ DEL : REPLY ]
    • http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL 을 이용하시면 알림을 선택했을 때 바로 없어지도록 할 수 있습니다~~

      2012/04/25 11:21 [ ADDR : EDIT/ DEL ]
  6. 포베

    제가 궁금했던것은 Ongoing으로 계속 알림패널에는 유지시키고 아이콘만 노티바에 안보이게 하는방법 이었습니다~ㅎㅎ

    2012/04/25 13:28 [ ADDR : EDIT/ DEL : REPLY ]
  7. jjaestory

    노티를 정 to the 벅! 했습니다. 감사합니다.

    2012/05/20 18:34 [ ADDR : EDIT/ DEL : REPLY ]
  8. captinpack

    AVD에서는 잘 되지만 겔S에서 실행하면 등록되었다는 토스트는 보여지지만 실제로 알림이 등록되지 않습니다.
    무슨 문제일까요?

    2012/06/16 10:16 [ ADDR : EDIT/ DEL : REPLY ]
    • 갤럭시S에서도 특별히 문제될 것 없을텐데요...
      저도 갤럭시S가 있어서 테스트 해 보았는데 특별한 문제는 없었습니다.

      2012/06/16 21:49 [ ADDR : EDIT/ DEL ]
  9. 89휴학생

    커니님 한 가지 질문이 있는데
    혹시 상태바 오른쪽 영역에 알림 아이콘 띄우는 방법이 있을까요?
    오른쪽 영역은 서비스 영역이라고 하던데..
    몇몇 어플들은 그 영역에 알림 아이콘이 뜨길래 질문 드립니다.

    2012/08/27 03:02 [ ADDR : EDIT/ DEL : REPLY ]
    • 온스크린 키보드를 만들 때 해당 영역에 아이콘을 띄울 수 있는 방법이 있기는 한데, 다른 곳에서도 해당 부분에 띄울 수 있는지까지는 잘 모르겠습니다 ^^;

      2012/08/28 02:13 [ ADDR : EDIT/ DEL ]
  10. idream

    아무리 읽어봐도 노티피케이션을 이해하기 힘듭니다.노티피케이션에 정의에대해서 말씀해주시면 안돼나요..;;

    2012/10/31 21:14 [ ADDR : EDIT/ DEL : REPLY ]
    • 단순히 '알림' 메시지라 생각하시면 됩니다.
      윈도우에서도 작업 표시줄 우측에 풍선 팝업들이 표시되면서 '하드웨어 설치 중', 과 같이 이벤트가 발생하면 알려주는데, 안드로이드의 알림도 그와 동일한 역할을 한다 이해하면 되겠네요~

      2012/11/06 21:56 [ ADDR : EDIT/ DEL ]
  11. 21

    여지껏 봤던 안드로이드 강좌중에 가장 탁월합니다...
    질문이있는데....
    Notification이 표시될 시각을 사용자가 설정한 시간에 띄우려고해서
    타입이 long when 으로 입력한 시간을 세팅해야하는데
    long when의 타입에 대한 정보가 아무리 검색해도 안나와요ㅠㅠ...

    long when 타입을 현재시각이 아닌 입력받으려면 어떻게 해야할까요??....

    2012/11/10 18:00 [ ADDR : EDIT/ DEL : REPLY ]
    • 지정한 시각에 알림이 뜨게 하려면 AlarmManager 등을 사용하여 현재로부터 일정 시간 후에 알림이 표시되도록 하는 방법을 사용하시면 됩니다. when은 알림이 표시될 때 옆에 같이 표시되는 '시각'만을 나타낼 뿐, 실제 알림이 표시되는 시각과는 관련이 없습니다.

      2012/11/20 23:55 [ ADDR : EDIT/ DEL ]
  12. 좋은글 출처를 표시하고 블로그에 담아갑니다. ^^

    2013/04/16 10:46 [ ADDR : EDIT/ DEL : REPLY ]
  13. 브라이언

    메시지를 여러줄로 나오게 하고 싶은데 옵티머스G는 \n 처리가 되서 두줄로 나오는 것 같은데요 겔럭시S3 에서는 한줄로 나오더라구요. 겔럭시 S3에서 메시지를 여러줄로 보이게 하려면 어떤 작업을 더 해주어야 할까요?

    2013/04/17 21:48 [ ADDR : EDIT/ DEL : REPLY ]
    • \n을 입력하면 여러 줄로 나오는 것이 정상입니다. 제대로 나오지 않는다면 기기 문제라는건데, 이 부분은 딱히 해결할 방법이 없습니다 (..)

      2013/04/20 10:25 [ ADDR : EDIT/ DEL ]
  14. 최용석

    감사합니다

    2013/05/14 11:31 [ ADDR : EDIT/ DEL : REPLY ]
  15. 초보자

    혹시 데이터베이스에 글이 추가되면 자동으로 알려주는 알림기능도 이 노티피케이션으로 가능한가요?
    싸이월드같이 새로운 글이 올라오면 알려주는 기능을 추가해주고 싶은데 어떤 방법을 써야하는지 잘모르겠네요..

    2013/06/12 15:41 [ ADDR : EDIT/ DEL : REPLY ]