일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- FLUTTER
- 준코딩
- 연결리스트
- text to speech
- 버블정렬
- storyboard
- 예외처리
- TextField
- 안드로이드스튜디오
- 안드로이드
- IOS
- label
- swift baekjoon
- xocde
- Swift
- 플러터
- deeplink
- 링크드리스트
- 백준
- Android
- 자바
- android java
- Xcode
- Android Studio
- C언어
- 커스텀팝업
- Firebase
- BAEKJOON
- 보호와 보안
- customPopup
- Today
- Total
준코딩
핑거푸시 연동하기 (FingerPush Android) 본문
안녕하세요~ 이번에는 핑거푸시 연동 방법에 대하여 작성하겠습니다.
(광고 같은건 아니고, 회사에서 이거 사용한다고 쓸수있게 연동해달라고해서 ㅇㅇ......그리고 인터넷에 검색해도 잘 안나오길래...)
이 겁니다.
https://www.fingerpush.com/index.jsp
사실 핑거푸시 자체 사이트에 연동 방법이 나와있긴합니다.
https://developers.fingerpush.com/app-push/sdk-manual/android
Android SDK 매뉴얼 - APP PUSH
data.code : CD:1;IM:0;PT:DEFT
developers.fingerpush.com
위 SDK 메뉴얼에 FCM APP 생성, 핑거푸시 사용자 콘솔 APP 생성은 간단하니 생략하고
SDK 적용하는 방법부터 작성 하겠습니다~.
1. build.gardle(Project) 파일에 아래 코드 추가해주세요 ~ (아마 신규 프로젝트가 아니면 작성 되어 있을 가능성이 높습니다)
여기 사이에 작성해주시면 됩니다.
dependencies{
classpath 'com.google.gms:google-services:4.3.15'
}
classpath 'com.google.gms:google-services:4.3.15'
2. build.gardle(Module) 파일에 아래 코드 추가해주세요 ~ (맨위나 아래나 아무대나 작성해주세요)
apply plugin: 'com.google.gms.google-services'
3. 위 SDK메뉴얼에서 다운받은 파일을 libs 파일 안에 넣어주세요!
만약 libs 폴더가 없으면 생성한 다음 넣어주세요~
4. build.gradle(Module) 파일의 dependencies 안에다가 저 라이브러리를 사용하겠다고 선언해줍시다~
(사실 아래 처럼 작성하면 libs 폴더 안에있는 확장자가 jar 이거나 aar인 라이브러리 전부다 사용하겠다고 작성하는 것입니다. 그래서 사실 핑거푸시 하나만 사용하겠다고 명시해서 작성하는게 좋긴합니다....)
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar", "*.aar"])
}
5. 핑거푸시 키 설정을 해줍시다.
저는 이 키 설정을 따로 클래스 생성해서 하지않고. 그냥 MainClass의 onCreate() 에서 호출해 주었습니다.
(appKey 값과, secretKey 값은 핑거푸시 사이트에서 앱 생성하고 나면 확인 가능합니다! 그대로 복사해서 넣어주세요)
FingerPushManager.setAppKey(String appKey);
FingerPushManager.setAppSecret(String secretKey);
6. Android13 이상부터 사용자에게 푸시권한을 직접 받아야하기 때문에 아래 코드 작성해줍시다
(AndroidManifest 에서 작성하면됩니다.)
이거 하고 build.gradle(Module) 에서 targetSdkVersion 33 으로 올려주셔야지 권한요청 팝업이 정상적으로 보여집니다.
(근데 이거 33으로 올렸더니 다이나믹링크가 정상작동이 안되었던..... 그래서 이거 관련 수정방법도 글 작성해서 올려두었습니다)
https://leejhjava.tistory.com/137
파이어베이스 다이나믹링크 Android13 버전 에러
안녕하세요. 사실 저번에 다이나믹링크 관련 작업을 하면서 android13 버전 이하에서는, 정상 작동이 되었는데 13버전 이상부터는 다이나믹 링크가 정상 작동이 되지 않는 문제가 있었습니다. 대충
leejhjava.tistory.com
<manifest ...>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<application ...>
...
</application>
</manifest>
7. 그리고 MainClass 에서 아래 코드 작성해 줍시다.
아래 코드 작성하고 onCreate() 에서 askNotificationPermission() 만 호출해줍시다.
// 핑거푸시 단말기 등록 (앱 실행 시 매번 호출되어야 합니다.)
private void setDevice() {
FingerPushManager.getInstance(this).setDevice(new NetworkUtility.ObjectListener() {
@Override
public void onComplete(String code, String message, JSONObject jsonObject) {
// code 200, 201 단말기 등록.
}
@Override
public void onError(String code, String message) {
// code 504 단말기가 이미 등록됨.
}
});
}
// 알림 권한 요청 결과
private final ActivityResultLauncher<String> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
setDevice()
});
// 알림 권한 요청
private void askNotificationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
// 이미 알림 권한이 허용된 상태
setDevice();
} else {
// 사용자에게 알림 권한 요청
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
}
} else {
setDevice();
}
}
8. 그리고 android8 이상부터는 알림채널을 생성해 주어야지 알림이 노출되기때문에 아래 코드도 같이 onCreate() 에다 작성해줍시다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.default_notification_channel_name);
fingerNotification.createChannel(channelId, channelName);
}
9. 그리고 알림 수신을 위해 Class 하나를 생성해 주어야합니다.
저는 MyFirebaseMessagingService 를 생성하여서 진행 하였습니다.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private Bitmap bmp = null;
OkHttpClient client = new OkHttpClient();
/**
* onNewToken 새롭게 토큰이 추가될때 실행
*/
public void onNewToken(String token) {
Log.d("FCM Log", "Refreshed token: " + token);
}
/**
* 알림이 왔을시 백그라운드,포그라운드인지 판단후에 작업 (getData만 사용하는게 현재는 옳은 예)
* 포그라운드일때 : onMessageReceived를 호출하여 메인에 onNewIntent를 호출 해당 페이지 이동
* 백그라운드일때 : 서버에서 날라온 데이터중에 "click_action" : "click_action"을 통해 앱을 새로 호출 해당 페이지 이동
* 참고사이트
* https://onedaycodeing.tistory.com/165
*/
@SuppressLint("CheckResult")
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("LJH","onMessageReceived()");
createNotificationChannel();
if (remoteMessage.getData() != null) {
try {
Log.d("LJH","onMessageReceived remoteMessage: " + remoteMessage.getData());
String title = remoteMessage.getData().get("data.title");
String message = remoteMessage.getData().get("data.message");
String weblink = remoteMessage.getData().get("data.weblink");
String imgUrl = remoteMessage.getData().get("data.imgUrl");
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("weblink", weblink);
intent.putExtra("imgUrl", imgUrl);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(message);
PendingIntent pendingIntent = null;
int notificationId = (int) System.currentTimeMillis();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity(this, notificationId, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
pendingIntent = PendingIntent.getActivity(this, notificationId, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
} else {
Log.d("LJH","SDK version is lower than M");
}
String channelId = "default_notification_channel_id";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setStyle(bigTextStyle)
.addAction(makeButtonInNotification(""))
.setOngoing(false)
.setContentIntent(pendingIntent);
if (!"".equals(imgUrl)) {
Uri uri = Uri.parse(remoteMessage.getData().get("data.imgUrl"));
if (getImage(uri)) {
notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bmp)
.bigLargeIcon(bmp));
}
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "알람설정";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("알림");
channel.enableLights(true);
channel.setLightColor(R.color.purple_overlay);
channel.enableVibration(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setShowBadge(true);
notificationManager.createNotificationChannel(channel);
}
int notiId = (int) System.currentTimeMillis();
notificationManager.notify(notiId, notificationBuilder.build());
if (bmp != null) {
bmp.recycle();
bmp = null;
}
} catch (Exception e) {
Log.e("FCM Log", "알림 Exception : " + e.getMessage());
}
}
}
/**
* 파이어베이스 remoteMessage를 통해 받은 url로 이미지 값 가져와 비트맵으로 변환하는 함수
* okhttp 라이브러리를 사용해서 Get 요청 동기처리
* 이미지를 받아오는데 실패했을 경우 false 반환
**/
public boolean getImage(Uri string) {
try {
// GET 요청을 Request.Builder 를 통해 만듦 (get 요청임을 명시)
Request request = new Request.Builder().url(String.valueOf(string)).get().build();
// client 객체의 newCall() 메소드에 만들어진 Request를 전달하고, execute() 메소드를 실행
Response response = client.newCall(request).execute();
// execute() 메소드는 요청에 대한 응답이 올때까지 기다렸다가 반환
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
ResponseBody in = response.body();
InputStream inputStream = in.byteStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
bmp = BitmapFactory.decodeStream(bufferedInputStream);
}
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* Notification(알림바)에 버튼을 추가
* 해당 버튼을 클릭하게 되면 알맞은 액션을 실행
* 추후에 필요시 사용
* @param action : 액션이름
* @return : Action
*/
public NotificationCompat.Action makeButtonInNotification(String action) {
// PendingIntent로 등록될 Intent 생성
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(action);
Log.d("LJH","pendingIntent 생성");
PendingIntent pendingIntent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
// Android 12 이상에서는 FLAG_IMMUTABLE 또는 FLAG_MUTABLE 중 하나를 명시해야 함
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
// Android 6.0 이상에서는 FLAG_MUTABLE을 사용할 필요가 없음
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
} else {
// Android 5.1 이하에서는 PendingIntent를 생성하지 않음
Log.d("LJH","SDK version is lower than M");
}
// 임의의 버튼 아이콘 등록
int iconId = R.drawable.ic_stat_ic_notification;
return new NotificationCompat.Action.Builder(iconId, action, pendingIntent).build();
}
// 알림 채널 생성
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.d("LJH","createNotificationChannel()");
NotificationChannel channel = new NotificationChannel("default_notification_channel_id", "알람설정", NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}else {
Log.d("LJH","createNotificationChannel 오레오 버전 이하. 채널생성 실패");
}
}
}
위 와같이 작업해 주시면 핑거푸시 연동 작업은 끝이납니다~
'프로그래밍 > Android(JAVA)' 카테고리의 다른 글
GPS를 이용하여 현재 주소 구하기.(Android Java) (0) | 2023.06.28 |
---|---|
커스텀 팝업 생성하기 / CustomDialog (0) | 2023.06.26 |
파이어베이스 다이나믹링크 Android13 버전 에러 (0) | 2023.06.26 |
Pull to Refresh 당겨서 새로고침 (0) | 2023.04.26 |
Android(java) 앱 버전 업데이트 빌드 에러[The destination foler does not exist or is not writeable] (2) | 2023.04.05 |