Program/Android Java

안드로이드 - Notification

너구리V 2012. 6. 12. 17:28


Notification은 특정 정보를 사용자에게 통지하기 위해 상태바(status bar)에 아이콘이나 문자열로 표시하거나 경고음, 진동으로 알리는 것이다.

상태를 drag하면 표시영역이 넓어져 (확장된 상태바) notification 상세내용이 표시된다.
확장된 상태바를 tap하면 설정한 intent (Pending Intent)가 발행되고, 이 intent에 activity를 지정하여 화면에 표시할 수 있다.


Notification 발행 Activity


public class NotificationActivity extends Activity {

    // 상태바에 일시적으로 표시되는 문자열
    private String tickerText = "cooking";
    // 상태바 아이콘 위에 겹쳐서 표시되는 숫자. 이벤트가 일어난 회수 표시.
    private int noticeNumber = 3;
    // 확장된 상태바에 나타낼 제목과 내용
    private String contentTitle = "Today";
    private String contentText = "Have a good day.";
 
 
    // NOTIFICATION_SERVICE의 매니저
    private NotificationManager mManager;
    // 마지막으로 발행한 Notification의 ID
    private int mLastId = 0;
    // 현재 등록되어있는 ID
    private List<Integer> mActiveIdList = new ArrayList<Integer>();


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Notification Manager
        mManager = (NotificationManager)
                             getSystemService(Context.NOTIFICATION_SERVICE);

        
        // Notification 발행 버튼
        Button b = (Button)findViewById(R.id.notify);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sendNotification();
            }
        });
        
        // Notification 취소 버튼
        b = (Button)findViewById(R.id.cancel);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                cancelNotification();
            }
        });
    }
    
    // Notification 발생
    private void sendNotification() {
        // Notification 생성
        Notification n = new Notification();
        // 아이콘의 설정
        n.icon = R.drawable.icon;

        // tickerText의 설정
        n.tickerText = tickerText;
        // 발생 날짜 설정
        n.when = new Date().getTime();
        // 발생 수량 설정
        n.number = noticeNumber;

        // 확장된 상태 표시줄 표시 설정
        n.setLatestEventInfo(
            getApplicationContext(),
            contentTitle,
            contentText,
            pendingIntent());

        // Notification 발생
        mManager.notify(createNotificationId(),n);
    }

    // Notification이 Tap 되었을 때에 발생되는 인텐트
    private PendingIntent pendingIntent() {
        // 이동할 화면의 Activity
        Intent i = new Intent(getApplicationContext(), PendingIntentActivity.class); 
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
        return pi;
    }

    // 발생하는 Notification의 ID를 생성
    private int createNotificationId() {
        int id = ++mLastId;
        mActiveIdList.add(id);
        return id;
    }

    //  Notification을 취소
    private void cancelNotification() {
        if (mActiveIdList.isEmpty())
            return;
        int id = mActiveIdList.remove(0);
        mManager.cancel(id);
    }
}









반응형