푸시 서비스 사용하기
activity_main.mxl
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="인스턴스 id 확인하기" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="30sp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="@android:color/holo_blue_bright">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>
</ScrollView>
1단계:화면 레이크아웃 만들기
이 수신 앱에서는 단말에서 클라우드 서버에 등록하여 ID를 받는 기능과 함꼐 메시지를 받는 기능을 만들어주어야 합니다
최상위 레이아웃을 LinearLayout으로 변경하고 orientation 속성 값은 vertical로 설정합니다.화면에는 버튼 하나와 텍스트뷰 하나를 추가하고 버튼에는 '인스턴스 id확인하기'라는 글자가 표시되록합니다,ScrollView를 추가하고 그안에 TextView를 넣어줍니다,스크롤뷰의 배경색은 밝은 파란색으로 바꾸어 영역이 구분되도록 하고 버튼 아래쪼게 있는 텍스트뷰와 그아래에 있는 텍스트뷰의 글자 크기는 30sp로 설정하고 스크롤뷰 안에 들어있는 글자 크기는 20sp로 합니다
MainActivity.java
package org.techtown.push;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class MainActivity extends AppCompatActivity {
TextView textView;
TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView2 = findViewById(R.id.textView2);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w("Main", "토큰 가져오는 데 실패함", task.getException());
return;
}
String newToken = task.getResult();
println("등록 id : " + newToken);
}
});
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String instanceId = FirebaseInstanceId.getInstance().getId();
println("확인된 인스턴스 id : " + instanceId);
}
});
}
public void println(String data) {
textView2.append(data + "\n");
Log.d("FMS", data);
}
@Override
protected void onNewIntent(Intent intent) {
println("onNewIntent 호출됨");
if (intent != null) {
processIntent(intent);
}
super.onNewIntent(intent);
}
private void processIntent(Intent intent) {
String from = intent.getStringExtra("from");
if (from == null) {
println("from is null.");
return;
}
String contents = intent.getStringExtra("contents");
println("DATA : " + from + ", " + contents);
textView.setText("[" + from + "]로부터 수신한 데이터 : " + contents);
}
}
2단계:소스 코드에 단말 등록 기능 추가하기
등록id가 확인되었을 떄 그 값을 받아 처리하기를 원한다면 FirebaseMessaging 객체의 getInstance메서드를 호출 한후 addOnCompleteListener메서드를 이용해 리스너를 등록합니다.그러면 등록 id가 확인되었을 떄 onSuccess메서드가 자동으로 호출됩니다.메서드 안에서 확인된 등록 id값을 화면에 있는 텍스트뷰에 출력합니다.화면에 있는 버튼을 눌럿을 떄는 FirebaseinstanceId객체의getId메서드를 호출하여 인스턴스 id를 확인합니다.
MyFirebaseMessagingService
package org.techtown.push;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.Map;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FMS";
public MyFirebaseMessagingService() {
}
@Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.d(TAG, "onNewToken 호출됨 : " + token);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "onMessageReceived 호출됨.");
String from = remoteMessage.getFrom();
Map<String, String> data = remoteMessage.getData();
String contents = data.get("contents");
Log.d(TAG, "from : " + from + ", contents : " + contents);
sendToActivity(getApplicationContext(), from, contents);
}
private void sendToActivity(Context context, String from, String contents) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("from", from);
intent.putExtra("contents", contents);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
3단계:소스 코드에 메시지 수신 기능 추가하기
애플리케이션 서버나 앱에서 메세지를 전송하면 클라우드 서버로 보낸 메시지는 수신 앱에서 받게 됩니다.앱에서 푸시 메시지를 받으면 MyFirebaseMessagingService 안에 들어 있는 onMessageReceived 메서드가 호출됩니다 메서드가 호출될 떄 전달되는 Remote<essage 객체의 정보를 확인하면 상대방이 클라우드 서버를 통해 보낸 푸시 메세지의 데이터를 확인할 수 있습니다,.푸시 메시지를 보낼 떄 contents를 키(Key)로 하여 사용자가 입력한 글자를 넣은 후 보낼 것이므로 메시지를 받을 때도 contents를 키로 확인할 수 있습니다.푸시 메시지를 받았을 떄 RemoteMessage 객체의 getFrom 메서드를 사용하면 어디에서 전송한 것인지 발신자 코드를 확인할 수 있습니다.getData 메서드를 사용하면 메시지를 전송할 떄 넣었던 데이터를 확인할 수 있습니다.getData메서드를 호출했을 떄 반환되는 것은 Map 객체이며 안에 들어 있는 데이터를 contents 키로 꺼내면 사용자가 입력했던 발신 데이터를 확인할 수 있습니다.