티스토리 뷰

안드로이드 노티피테이션 알림메시지 구현하기 

// 알림을 필요한 클래스 
// NotificationManager : NotificsationManager가 알림을 발생
// Notification : 알림객체
// NotificationCompat.Builder : 알림을 생성
// NotificationChannel : 알림을 관리하는 단위

 

1. xml 에 버튼 3개 추가하기 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notification 구현하기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.073" />

    <Button
        android:id="@+id/button_noti"
        android:layout_width="312dp"
        android:layout_height="53dp"
        android:layout_marginTop="72dp"
        android:onClick="btn_Click"
        android:text="가본 Notification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.504"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_intent_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:text="Notification을 통해 액티비티 실행하기"
        android:onClick="btn_pending_click"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_noti" />

    <Button
        android:id="@+id/button_style"
        android:layout_width="312dp"
        android:layout_height="51dp"
        android:onClick="btn_image"
        android:text="큰 이미지보기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.504"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_intent_btn"
        app:layout_constraintVertical_bias="0.19" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

2. MainActivity.java 

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    // 알림을 필요한 클래스 - 시스템서비스를 통해
    // NotificationManager : NotificsationManager가 알림을 발생
    // Notification : 알림객체
    // NotificationCompat.Builder : 알림을 생성
    // NotificationChannel : 알림을 관리하는 단위

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void btn_Click(View view){

    }

    public void btn_pending_click(View view){

    }

    public void btn_image(View view){

    }
}

 

3. 추가

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    // 알림을 필요한 클래스 - 시스템서비스를 통해
    // NotificationManager : NotificsationManager가 알림을 발생
    // Notification : 알림객체
    // NotificationCompat.Builder : 알림을 생성
    // NotificationChannel : 알림을 관리하는 단위

    NotificationManager notificationManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 기본 Notification
    public void btn_Click(View view){
        
                

    }

    public void btn_pending_click(View view){

    }

    public void btn_image(View view){

    }

    // NotificationCompat.Bilder를 이용해서 생성한다.
    // Notification객체가 안드로이드 버전별로 바뀐 부분이 있다 .
    // NotificationChannel을 통해서 알림메시지를 관리한다.
    // 알림이 네트워크에 관련된 것인지 저장에 관련된 것인지 구분하기 위해서 작업한다.
    public NotificationCompat.Builder getBuilder(String channel_id, String channel_name) {
        // 낮은 버전을 사용하는 경우 8.0부터 채널을 통해서 관리한다 .
        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  //오레오버젼 안드로이드 8.0
            // 채널을 생성하고 등록한다.
            NotificationChannel channel = new NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_HIGH);

            channel.enableLights(true); // LED 사용유무
            channel.setLightColor(Color.RED);
            channel.enableVibration(true);  // 진동

            //NotificationManager를 통해서 채널을 등록한다. - Builder에 의해서 만들어진 Notification은 채널에 의해 관리 된다 .
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, channel_id);
        }else {
            // 이전버전 Builder 를 얻어오기
            builder = new NotificationCompat.Builder(this, channel_id);
        }

        return builder;
    }
}

 

4.  완료 

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    // 알림을 필요한 클래스 - 시스템서비스를 통해
    // NotificationManager : NotificsationManager가 알림을 발생
    // Notification : 알림객체
    // NotificationCompat.Builder : 알림을 생성
    // NotificationChannel : 알림을 관리하는 단위

    NotificationManager notificationManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 기본 Notification
    public void btn_Click(View view){
        NotificationCompat.Builder builder = getBuilder("channel_1", "dataManager");
        //이미지설정
        builder.setSmallIcon(android.R.drawable.ic_notification_overlay);
        //제목설정
        builder.setContentTitle("Notificatio 연습_기본");
        builder.setContentText("5cm근방에 접급했습니다.");

        //이미지 추가하기
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.search);
        builder.setLargeIcon(bitmap);

        //알림과 동시에 스마트폰에 진동이 울리도록 처리
        builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);

        //Notification 객체를 만들기
        Notification notification = builder.build();
        //Notification객에를 NotificationManager에 등록 - Notification을 발생
        notificationManager.notify(1004,notification);


    }

    public void btn_pending_click(View view){
        NotificationCompat.Builder builder = getBuilder("channel_1", "dataManager");
        //이미지설정
        builder.setSmallIcon(android.R.drawable.ic_notification_overlay);
        //제목설정
        builder.setContentTitle("Notificatio 연습_기본");
        builder.setContentText("5cm근방에 접급했습니다.");

        //이미지 추가하기
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.search);
        builder.setLargeIcon(bitmap);

        //알림과 동시에 스마트폰에 진동이 울리도록 처리
        builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);

       // Notificiation을 클릭하면 액티비티를 실행할 수 있도록 처리
        //1. Intent를 만든다.
        Intent intent = new Intent(this, MainActivity2.class);
        //2. PendingIntent를 만든다.
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 100,intent, PendingIntent.FLAG_MUTABLE );
          // FLAG_UPDATE_CURRENT : 현재 내용으로 이전 객체 업데이트
        // FLAG_CANCEL_CURRENTE : 이전에 생성된 PendingIntent를 취소하고 다시 만들기
        //Builder객체에 PendingIntetn를 설정
        builder.setContentIntent(pendingIntent);




        //Notification 객체를 만들기
        Notification notification = builder.build();
        //Notification객에를 NotificationManager에 등록 - Notification을 발생
        notificationManager.notify(1004,notification);
    }

    public void btn_image(View view){
        NotificationCompat.Builder builder = getBuilder("bigImage","noti_bigImage");
        //안드로이드 이미지설정
        builder.setSmallIcon(android.R.drawable.ic_notification_overlay);
        //제목설정
        builder.setContentText("Style연습");
        builder.setContentText("이미지가 보이는 Notification");
        //이미지 추가하기
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.search);
        builder.setLargeIcon(bitmap);
        //알림과 동시에 스마트폰에 올리도록 처리
        builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);

        //Notification 객체를 만들기
        Notification notification = builder.build();
        //Notification객에를 NotificationManager에 등록 - Notification을 발생
        notificationManager.notify(1004,notification);
    }

    // NotificationCompat.Bilder를 이용해서 생성한다.
    // Notification객체가 안드로이드 버전별로 바뀐 부분이 있다 .
    // NotificationChannel을 통해서 알림메시지를 관리한다.
    // 알림이 네트워크에 관련된 것인지 저장에 관련된 것인지 구분하기 위해서 작업한다.
    public NotificationCompat.Builder getBuilder(String channel_id, String channel_name) {
        // 낮은 버전을 사용하는 경우 8.0부터 채널을 통해서 관리한다 .
        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  //오레오버젼 안드로이드 8.0
            // 채널을 생성하고 등록한다.
            NotificationChannel channel = new NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_HIGH);

            channel.enableLights(true); // LED 사용유무
            channel.setLightColor(Color.RED);
            channel.enableVibration(true);  // 진동

            //NotificationManager를 통해서 채널을 등록한다. - Builder에 의해서 만들어진 Notification은 채널에 의해 관리 된다 .
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, channel_id);
        }else {
            // 이전버전 Builder 를 얻어오기
            builder = new NotificationCompat.Builder(this, channel_id);
        }

        return builder;
    }
}
댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
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
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글