0

관리자가 블로그를 게시 할 때 앱을 사용하는 모든 사용자에게 알림을 보내야하는 Android 블로그 앱을 개발 중입니다.Firebase 기능을 사용하여 여러 사용자에게 알림을 보내는 중 오류가 발생했습니다.

관리자가 블로그를 게시 할 때 알림이 전송되지 않습니다. 이

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

exports.pushNotification = functions.database.ref('/notifications/{pushId}').onWrite(event => { 

    console.log('Push notification event triggered'); 


    var valueObject = event.data.val(); 
     const titleIs = event.params.pushId; 

     console.log('Title is: ', titleIs); 

    const payload = { 
     notification: { 
       title : "New status Update", 
       body: "There is a new status for you!", 
       icon: "default"    
     }, 
    }; 

    const options = { 
     priority: "high", 
     timeToLive: 60 * 60 * 24 
    }; 

    return admin.messaging().sendToTopic("pushNotifications", payload, options) 
     .then(function(response) { 
      console.log("Successfully sent notification: ", response.message); 
     }) 
     .catch(function(error) { 
      console.log("Error sending notification: ", error) 
     }); 
}); 

서비스를위한 자바 파일 : 여기 nodejs를 사용하고하면 코드 관리자가 블로그를 게시 코드는 여기

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "FirebaseMessagingServce"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 

     String notificationTitle = null, notificationBody = null; 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
      notificationTitle = remoteMessage.getNotification().getTitle(); 
      notificationBody = remoteMessage.getNotification().getBody(); 
     } 

     // Also if you intend on generating your own notifications as a result of a received FCM 
     // message, here is where that should be initiated. See sendNotification method below. 
     sendNotification(notificationTitle, notificationBody); 
    } 


    private void sendNotification(String notificationTitle, String notificationBody) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
       .setAutoCancel(true) //Automatically delete the notification 
       .setSmallIcon(R.mipmap.ic_launcher) //Notification icon 
       .setContentIntent(pendingIntent) 
       .setContentTitle(notificationTitle) 
       .setContentText(notificationBody) 
       .setSound(defaultSoundUri); 


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

     notificationManager.notify(0, notificationBuilder.build()); 
    } 
} 

가되고

private void startPosting() { 

     mProgressDialog.setMessage("Posting to Status ..."); 

     final String title_value = mStatusTitleEditText.getText().toString().trim(); 
     final String description_value = mStatusDescriptionEditText.getText().toString().trim(); 

     if (!TextUtils.isEmpty(title_value) && !TextUtils.isEmpty(description_value) 
       && mImageUri != null) { 

      mProgressDialog.show(); 

      StorageReference mFilePath = 
        mStorage.child("Status_Images").child(mImageUri.getLastPathSegment()); 

      mFilePath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask 
        .TaskSnapshot>() { 
       @Override 
       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 

        //DB 
        HashMap<String, String> notificationData = new HashMap<>(); 
        notificationData.put("from", "admin"); 

        mNotificationDatabase.push().setValue(notificationData) 
          .addOnSuccessListener(new OnSuccessListener<Void>() { 
         @Override 
         public void onSuccess(Void aVoid) { 
          Toast.makeText(PostActivity.this, "Added to database", 
            Toast.LENGTH_SHORT).show(); 
         } 
        }); 

        @SuppressWarnings("VisibleForTests") 
        Uri downloadUrl = taskSnapshot.getDownloadUrl(); 

        DatabaseReference newPost = mDatabase.push(); 
        newPost.child("title").setValue(title_value); 
        newPost.child("description").setValue(description_value); 

        newPost.child("date").setValue(System.currentTimeMillis()); 

        newPost.child("image").setValue(downloadUrl.toString()); 


        mProgressDialog.dismiss(); 

        FirebaseMessaging.getInstance().subscribeToTopic("pushnotifications"); 

        startActivity(new Intent(PostActivity.this, MainActivity.class)); 
       } 
      }); 
     } 
    } 
+1

함수에 문제가있는 것은 확실합니까? 클라이언트 측에서도 메시징 구현에 문제가있을 수 있습니다. –

+0

감사! 로그를 확인했는데 기능에 문제가 없었습니다. 내 질문을 편집했습니다. –

+0

정의한 옵션을 사용하고 있지 않습니다. [sendToTopic()] (https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#sendToTopic) 호출에서 세 번째 인수로 전달하십시오. sendToTopic ("pushNotifications", 페이로드, 옵션)'. 이것은 아마도 주요 문제는 아니지만 우선 순위를 포함하면 기기가 잠 들어있을 때 메시지가 전달됩니다. –

답변

0

토픽 이름 사용에 오타가 있습니다. 클라우드 기능에서 게시자는 pushNotifications입니다. 앱에서 주제 pushnotifications (모두 소문자)을 구독하고 있습니다.

+0

오타가 수정되었지만 여전히 성공하지 못했습니다. –

+0

logcat에서 'W/GooglePlayServicesUtil : 오래된 Google Play 서비스'라는 경고를 확인하십시오. –