Android 알림, PendingIntent 예제
Android PendingIntent를 사용하는 Android 알림 예제에 오신 것을 환영합니다. 이 튜토리얼에서는 PendingIntent
에 대해 논의 및 구현하고 애플리케이션에서 Notification
을 빌드할 것입니다.
안드로이드 보류 의도
Android PendingIntent는 BroadcastReceiver 또는 서비스를 래핑하는 개체입니다. 따라서 PendingIntent는 다음 메서드를 사용하여 다양한 유형의 의도를 처리합니다.
PendingIntent.getActivity()
: PendingIntent를 검색하여 활동 시작PendingIntent.getBroadcast()
: 브로드캐스트를 수행하기 위해 PendingIntent를 검색합니다.PendingIntent.getService()
: PendingIntent를 검색하여 서비스 시작
PendingIntent의 구현 예는 다음과 같습니다.
Intent intent = new Intent(this, SomeActivity.class);
// Creating a pending intent and wrapping our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
// Perform the operation associated with our pendingIntent
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
pendingIntent와 관련된 작업은 send()
메서드를 사용하여 실행됩니다. getActivity() 메서드 내부의 매개변수와 사용법은 다음과 같습니다.
- this (context) : PendingIntent가 활동을 시작하는 컨텍스트입니다.
- requestCode: "1”은 위의 예에서 사용된 보낸 사람의 개인 요청 코드입니다. 나중에 동일한 메서드로 다시 사용하면 동일한 보류 중인 의도를 반환합니다. 그런 다음 보류 중인 의도를 취소하는 등 다양한 작업을 수행할 수 있습니다. 취소() 등으로.
- intent : 시작할 액티비티의 명시적 인텐트 객체
- 플래그 : 위의 예제에서 사용한 PendingIntent 플래그 중 하나는 FLAG_UPDATE_CURRENT입니다. 이것은 이전 PendingIntent가 이미 존재하는 경우 현재 PendingIntent가 최신 의도로 업데이트한다고 말합니다. FLAG_CANCEL_CURRENT 등과 같은 다른 많은 플래그가 있습니다.
안드로이드 알림
Android Toast 클래스는 사용자에게 알림을 표시하는 편리한 방법을 제공하지만 문제는 이러한 알림이 지속되지 않는다는 것입니다. 즉, 알림이 화면에서 몇 초 동안 깜박인 다음 사라집니다. 이러한 상황에서 Android 알림 메시지는 빈 공간을 채웁니다. Android 알림은 애플리케이션의 일반 UI 외부에서 사용자에게 표시할 수 있는 메시지입니다. Android의 알림은 NotificationCompat
라이브러리를 사용하여 빌드됩니다.
Android 알림 만들기
알림은 아래와 같이 NotificationManager
클래스를 사용하여 생성됩니다.
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification.Builder
는 아래와 같이 알림 객체를 생성하기 위한 빌더 인터페이스를 제공합니다.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
Android 알림 방법
이 빌더 개체에 대한 알림 속성을 설정할 수 있습니다. 자주 사용되는 몇 가지 방법과 그에 대한 설명이 아래에 나와 있습니다.
-
Notification build() : Combines all of the options that have been set and returns a new Notification object
-
NotificationCompat.Builder setAutoCancel (boolean autoCancel) : Setting this flag will make it such that the notification is automatically canceled when the user clicks it in the panel
-
NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard one
-
NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notification
-
NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clicked
-
NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notification
-
NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notification
-
NotificationCompat.Builder setDefaults (int defaults) : Sets the default notification options that will be used. An example is;
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
-
NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is shown in the ticker and notification
-
NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notification
-
NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notification
-
NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layouts
-
NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build time
-
NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that is displayed in the status bar when the notification first arrives
-
NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to use
-
NotificationCompat.Builder setWhen (long when) : Sets the time that the event occurred. Notifications in the panel are sorted by this time
Android 알림 버튼 및 스타일
Notification.Builder
를 사용하면 정의 가능한 작업이 포함된 최대 3개의 버튼을 알림에 추가할 수 있습니다. Android 4.1 이상에서는 알림이 확장될 때 크게 표시되는 확장 가능한 알림을 지원합니다. 큰 그림 스타일, 큰 텍스트 스타일, 받은 편지함 스타일의 세 가지 스타일을 큰 보기와 함께 사용할 수 있습니다.
Android 알림 취소
NotificationManager
의 특정 알림 ID에 대해 cancel()
을 호출할 수도 있습니다. cancelAll()
메서드 호출은 이전에 발행한 모든 알림을 제거합니다. 이 튜토리얼에서는 웹페이지를 보는 인텐트를 PendingIntent로 래핑하는 애플리케이션을 만들 것입니다. 해당 PendingIntent는 알림을 탭할 때 실행됩니다. 또한 프로그래밍 방식으로 알림을 취소하는 기능도 추가할 예정입니다.
Android 알림 예제 프로젝트 구조
Android 알림 예
activity_main.xml은 두 개의 버튼이 있는 기본 상대 레이아웃입니다. 하나는 알림을 생성하고 다른 하나는 알림을 취소합니다. activity_main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.journaldev.notifications.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CREATE NOTIFICATION"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CANCEL NOTIFICATION"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
MainActivity.java
는 아래와 같습니다.
package com.journaldev.notifications;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnClick(R.id.button)
public void sendNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
@OnClick(R.id.button2)
public void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.cancel(1);
}
}
Android PendingIntent 및 알림 프로젝트 다운로드
참조:
- https://developer.android.com/reference/android/app/PendingIntent.html
- https://developer.android.com/guide/topics/ui/notifiers/notifications.html