android - 收到fcm通知后自动启动activity?

标签 android push-notification firebase-cloud-messaging

我想在收到 fcm 推送通知后自动启动一个特定的 Activity 。点击它可以正常工作,但我想在收到通知后自动启动它。这是我的代码

我触发代码的 FirebaseMessagingService 方法

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

private NotificationUtils notificationUtils;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());
//changes for notification on 9/11/2017
//        if(remoteMessage.getNotification().getBody()!=null) {
       // Log.e(TAG, "Message Body: " + remoteMessage.getNotification().getBody());
    //}
    //showNotificationMessage(remoteMessage.getNotification().getBody());
//        String click_action=remoteMessage.getNotification().getClickAction();
   // Intent i=new Intent(click_action);
 ////////////////////////////////////////
        if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());

        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "AllCallsData Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            Handler mHandler;
            //mHandler = new Handler() {
                handleDataMessage(json);
            //};
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
        NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
        //Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.);
        //Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        //r.play();
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

    private void handleDataMessage (JSONObject json){

        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            //String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");

            JSONObject payload = data.getJSONObject("payload");
            OpenTokConfig.SESSION_ID = payload.getString("session_id");
            OpenTokConfig.API_KEY = payload.getString("api_key");
            OpenTokConfig.TOKEN = payload.getString("token_id");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);

            //Log.e(TAG, "payload: " + payload.toString());
            //Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);
            Intent i = new Intent(Config.CLICK_ACTION);
            showNotificationMessage(getApplicationContext(), title, message, timestamp, i);


            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
                Common.call_recvd = true;
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), RegistrationActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
           /* if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }*/
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }


/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    //startActivity(intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}

}

MyNotification Utils 类代码

public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");

    if (!TextUtils.isEmpty(imageUrl)) {

        if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

            Bitmap bitmap = getBitmapFromURL(imageUrl);

            if (bitmap != null) {
                showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            } else {
                showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            }
        }
    } else {
        showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
        playNotificationSound();
    }
}

最佳答案

您可以使用广播接收器实现此目的,因此当您收到通知时只需发送广播,而在接收广播时您可以编写与启动 Activity 相关的代码。

使用它发送广播。

Intent intentNotification = new Intent();
intentNotification.setAction("com.from.notification");
sendBroadcast(intentNotification);

使用这个注册你的广播接收器:

getActivity().registerReceiver(broadcastReceiver,
                new IntentFilter("com.from.notification"));

接收广播:

private BroadcastReceiver broadcastReceiver;
broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // do your stuff related to start activity
            }
        };

关于android - 收到fcm通知后自动启动activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47386221/

相关文章:

java - 如何知道从动态添加的 View 中单击了哪些切换按钮?

java - 如何删除从移动设备清除应用程序数据后触发的通知

iphone - Apple 推送通知增强格式

android - Android Firebase 通知没有自定义声音

android - 使用 Firebase 处理后台推送通知,支持 Doze

android - 关机和开机后的AlarmManager对象

android - 无法直接启动定义和强制执行自定义权限的应用程序

java - 验证根访问权限 : How to do?

android - 解析 GCM 事件中的时间戳时出错 - Null Android(未调用 onMessageReceived)

swift - 在 iOS 10 上使用 UNUserNotificationCenter