본문 바로가기
안드로이드 자바

[JAVA][Android] notification에 값 담아전달하기

by teamnova 2022. 3. 12.

이번시간에는  버튼을 눌러 노티피케이션을 생성하고,

노티를 눌러이동시 값을 전달하는 예제를 만들어 볼까요?

 

하단 스틱코드를 즐겨찾기 해주세요~

https://stickode.com/detail.html?no=2800 

 

https://stickode.com/detail.html?no=2800

 

stickode.com

 

오늘 만들예제를 미리 살펴보겠습니다.

startActivity - 노티피케이션 알림띄우기 버튼을 두번 누르면, 2 라는 값을 count에 담아서 노티로 전달합니다.

ResultActivity - 노티를 눌러 넘어간 액티비티에서 전달받은 값2를 확인할수 있습니다.

 

 

1.액티비티에 노티피케이션을 생성하기 위한 버튼을 만듭니다.

2.노티피케이션 매니저와 , 노티피케이션 채널을 생성합니다.

3.그리고 노티피케이션 빌더를 생성하고

4.노티피케이션매니저로 노티피케이션을 전달하면 노티에 값을 담아 보낼수 있습니다.

5.매니페스트에 등록을 해줍니다.

 

startActicity - 버튼을 누르는 액티비티 

package com.example.myapplication.ATest;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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

import com.example.myapplication.R;

/**
 * 1. NotificationManager , Notification Channel 생성
 *
 * 2. Notification Builder 생성
 *
 * 3. NotificationManager 로 Notification 전달
 */
public class startActivity extends AppCompatActivity {

    // 채널에 대한 ID생성 - 채널을 구분하기 위한 아이디입니다.
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private int count = 0;


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

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                // 버튼을 누를때마다 count 를 증가시킴
                // 카운트를 세번누르면 3이라는 숫자가 전달됨
                count++;
                NotificationSomethings();
            }
        });
    }

    public void NotificationSomethings() {

        // 채널을 생성 및 전달해 줄수 있는 NotificationManager를 생성한다.
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        // 이동하려는 액티비티를 작성해준다.
        Intent notificationIntent = new Intent(this, ResultActivity.class);
        // 노티를 눌러서 이동시 전달할 값을 담는다. // 전달할 값을 notificationIntent에 담습니다.
        notificationIntent.putExtra("notificationId", count);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK) ;
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,  PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground)) //BitMap 이미지 요구
                .setContentTitle("오늘 뭐 먹지 ")
                .setContentText("상태바 드래그시 보이는 서브타이틀 " + count)
 
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent) // 사용자가 노티피케이션을 탭시 ResultActivity로 이동하도록 설정
                .setAutoCancel(true); // 눌러야 꺼지는 설정

        //OREO API 26 이상에서는 채널 필요
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            builder.setSmallIcon(R.drawable.ic_launcher_foreground); //mipmap 사용시 Oreo 이상에서 시스템 UI 에러남
            CharSequence channelName  = "노티페케이션 채널";
            String description = "오레오 이상";
            int importance = NotificationManager.IMPORTANCE_HIGH;// 우선순위 설정

            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName , importance);
            channel.setDescription(description);

            // 노티피케이션 채널을 시스템에 등록
            assert notificationManager != null;
            notificationManager.createNotificationChannel(channel);

        }else builder.setSmallIcon(R.mipmap.ic_launcher); // Oreo 이하에서 mipmap 사용하지 않으면 Couldn't create icon: StatusBarIcon 에러남

        assert notificationManager != null;
        notificationManager.notify(1234, builder.build()); // 고유숫자로 노티피케이션 동작

    }

}

 

 ResultActivity - 노티를 눌러이동한  액티비티( 값을 전달받음 )

package com.example.myapplication.ATest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;

import com.example.myapplication.R;

public class ResultActivity extends AppCompatActivity {

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


        // 노티피케이션 연습
        String text = "전달 받은 값은";
        int id = 0;

        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            text = "값 전달 받기 실패 ";
        }
        else
            id = extras.getInt("notificationId");

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(text + " " + id);

        NotificationManager notificationManager =  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //노티피케이션 제거
        notificationManager.cancel(id);
    }
}

 

activity_start.xml

<?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=".ATest.startActivity">

    <Button
        android:text="노티피케이션 알림창띄우기 "
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:backgroundTint="@color/design_default_color_secondary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="60dp"
        android:id="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

activity_result2.xml

<?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=".ATest.ResultActivity">

    <Button
        android:text=""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="70dp"
        android:id="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

매니페스트에 등록을 해주어야 사용할수 있습니다.

   <!-- 노티피케이션 결과를 보여줄 액티비티 선언 -->
        <activity
            android:name=".ATest.ResultActivity"
            android:parentActivityName=".ATest.startActivity" >
        </activity>

 

결과화면 입니다.