11

Firebase Cloud Messaging에 알림을 보내고 있습니다. 응용 프로그램이 열린 상태 일 때 이미 구현하고 알림을 수신합니다. 하지만 앱을 닫으면 알림이 더 이상 제공되지 않습니다. 이 문제에 대한 해결책이 있습니까?닫힌 경우 Android 앱에 FCM 알림이 수신되지 않음

코드 :

WebRequest wRequest; 
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); 
wRequest.Method = "post"; 
wRequest.ContentType = " application/json;charset=UTF-8"; 
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId)); 

wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId)); 

string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}"; 

Byte[] bytes = Encoding.UTF8.GetBytes(postData); 
wRequest.ContentLength = bytes.Length; 

Stream stream = wRequest.GetRequestStream(); 
stream.Write(bytes, 0, bytes.Length); 
stream.Close(); 

WebResponse wResponse = wRequest.GetResponse(); 

메시징 서비스 -

public class MessagingService extends FirebaseMessagingService { 
    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     Map<String, String> data = remoteMessage.getData(); 
     sendNotification(data); 
    } 

    public void showMessage(Map<String, String> serverData) { 
     Intent i = new Intent(this,MainActivity.class); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT); 

     NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
       .setAutoCancel(true) 
       .setContentTitle(serverData.get("Title")) 
       .setContentText(serverData.get("Message")) 
       .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark) 
       .setContentIntent(pendingIntent); 

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

     manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build()); 
    } 

    private void sendNotification(Map<String, String> serverData) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT); 

     long[] pattern = {500,500,500,500,500}; 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

     NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark) 
       .setContentTitle(serverData.get("Title")) 
       .setContentText(serverData.get("Message")) 
       .setAutoCancel(true) 
       .setVibrate(pattern) 
       .setLights(Color.BLUE,1,1) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build()); 
    } 

} 

주요 활동 -

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     FirebaseMessaging.getInstance().subscribeToTopic("test"); 
     FirebaseInstanceId.getInstance().getToken(); 
    } 
} 

Manifest-

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="test.com.firebasenotify"> 
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <service android:name=".MessagingService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.MESSAGING_EVENT" /> 
      </intent-filter> 
     </service> 
     <service android:name=".InstanceIDService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> 
      </intent-filter> 
     </service> 

    </application> 

</manifest> 
+1

표시 FCM 리스너 클래스 및 POST를 보여 당신이 적어도 onreceive에서 메시지를 수신합니까 –

+0

업데이트 메시징 서비스, FCM 포스트 및 주요 활동 코드 –

+0

를 FCM 할 수 있도록 요청? –

답변

8

코드에 문제가 없었습니다. Mi note 4를 사용하고 있었는데 응용 프로그램이 닫히면 Mi4에 알림이 표시되지 않습니다. 나는 다른 안드로이드 장치와 잘 작동하는지 테스트했습니다.

대화에 참여한 Tim Castelijns와 Frank van Puffelen에게 감사드립니다.

+2

MI의 경우 앱이 닫힐 때 알림을 받으려면 Security에 자동 시작 모드로 앱을 넣어야합니다. –

+0

redmi prime2도 같은 문제가 발생했습니다. MI 장치에서이 문제에 대한 해결책을 찾았습니까? – sandeepmaaram

-1

0 2,419,200 초까지의 기간이 있어야이 파라미터의 이러한 것은 문제도 값을 해결하는 것이다 POST 페이로드 time_to_live 키를 추가하며 FCM 저장 및 전달하기 위해 시도하는 최대 시간에 대응 메시지. "time_to_live": 3Refer Firebase Docs

+1

이것은 사용자가 응용 프로그램을 다시 사용할 때만 유효합니다. – ioanb7

-3

당으로 FCM 문서 onMessageReceived() 앱이 배경에있을 때가 호출되지 않습니다. 당신은 시스템 트레이에 표시하기 위해에 통지 객체를 전송해야하며, 사용자가 클릭하면 그것은 실행 활동엑스트라 의도로 데이터가 공개됩니다. 페이로드의 경우 데이터 개체를 사용해야합니다. see docsReceive Messages in an Android App

+2

코드가 없으면 알림 개체가 없습니다. 그는 단지 데이터 개체를 보내고 있습니다 –

+0

당신도 알림 개체를 보내야합니다. – Sjd

+2

하지만 알림 개체를 보내면 onMessageReceived에 도달하지 않고 알림이 android 자체에서 처리되고 알림 응용 프로그램 (클라이언트 응용 프로그램없이)에 표시됩니다. 그리고 만약 우리가 알림 개체없이 보내지 만 데이터 개체가 있으면 항상 onMessageReceived를 누르게됩니다. –