如果app在后台,如何使用fcm从服务器发送数据?

时间:2016-10-18 10:01:23

标签: java android firebase background firebase-cloud-messaging

我正在从服务器向我的应用发送fcm通知。

我从服务器发送包含user_id的数据。如果应用程序位于前台,我将在FirebaseMessageService类中获取此userId。但是,当应用程序处于后台时,不会得到它。由于FirebaseMessagingService类仅在应用程序位于前台时才会执行。

那么当应用程序处于后台时,我怎样才能获得此ID?

    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    private String mUserId;
    private Boolean mUpdateNotification;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        String clickAction = remoteMessage.getNotification().getClickAction();

        mUserId = remoteMessage.getData().get("user_id");

        String title = remoteMessage.getNotification().getTitle();

        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody(),clickAction,title);
    }

    //This method is only generating push notification
    //It is same as we did in earlier posts
    private void sendNotification(String messageBody,String clickAction,String title) {

        mUpdateNotification = true;

        Intent intent = new Intent(clickAction);

        intent.putExtra("userId",mUserId);
        intent.putExtra("updateNotification",mUpdateNotification);

        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 = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

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

编辑:

我正在使用仍然onMessageReceived的数据有效负载当app在后台时不会被调用。

 public function sendPush($text, $tokens, $apiKey,$user_id)
{

    $notification = array(
        "title" => "User updated profile.",
        "text" => $text,
        'vibrate' => 3,
        "click_action" => "OPEN_ACTIVITY_2",
        'sound' => "default",
        'user_id' => $user_id
    );

    $data = array("user_id" => $user_id);

    $msg = array
    (
        'message' => $text,
        'title' => 'User updated profile.',
        'tickerText' => 'New Message',
    );
    $fields = array
    (
        'to' => $tokens,
        'data' => $data,
        'notification' => $notification
    );

    $headers = array
    (
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    $result = curl_exec($ch);
    //  echo($result);
    //    return $result;
    curl_close($ch);
}

有人可以帮忙吗?谢谢..

2 个答案:

答案 0 :(得分:8)

我明白了。在您的有效负载中,您使用$('#link').click(function() { // we want to copy the 'id' from the button to the modal var target = $(this).attr('target'); var id = $(this).data('id'); $(target).data('id', id); }); $('#savebutton').click(function() { // now we grab it from the modal var id = $('#addBookDialog').data('id'); console.log(id); }); notification有效负载,这会在应用处于后台时更改您应该接收详细信息的位置。在我在评论中提到的doc中,您可以在摘要中看到两者是否包含在有效负载中:

  

数据:意图的额外内容。

更具体地说:

  

处理背景应用中的通知消息

     

当您的应用在后台时,Android会将通知消息定向到系统托盘。用户点按通知会默认打开应用启动器。

     

这包括包含通知和数据有效负载的消息(以及从通知控制台发送的所有消息)。在这些情况下,通知会传送到设备的系统托盘,而数据有效负载会在启动器活动的附加内容中传送。

我认为@ArthurThompson的answer解释得非常好:

  

当您发送带有数据有效负载(通知和数据)的通知消息并且应用程序位于后台时,您可以从用户点击通知而启动的意图的附加内容中检索数据。

     

点击通知后,FCM sample启动MainActivity:

data

答案 1 :(得分:0)

在清单

中注册您的服务
    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service> 

您可以检查应用是否在前景中

    public static boolean CheckAppIsRunningForground(Context mcontext) {

    ActivityManager am = (ActivityManager) mcontext
            .getSystemService(mcontext.ACTIVITY_SERVICE);

    // get the info from the currently running task
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

    ComponentName componentInfo = taskInfo.get(0).topActivity;
    if (componentInfo.getPackageName().equalsIgnoreCase(<YOUR PACKAGE>)) {
        return true;
    } else {
        return false;
    }

}

并在onMessageReceived

中添加此代码
    Boolean IsForground = CheckAppIsRunningForground(AgentService.this);
    if (IsForground) {

                  //App is FourGround

                } else {
                     sendNotification(remoteMessage.getNotification().getBody(),clickAction,title);
                }