android - 当应用程序以不同方式打开/关闭时显示推送通知

标签 android push-notification google-cloud-messaging android-broadcast

在我的应用程序中,我有几个继承自一个 BaseActivity 的 Activity 。
我的应用程序通过 GCMBaseIntentService
接收推送通知 我需要实现下一个逻辑:
当应用程序打开时收到推送时显示对话框,如果关闭则显示通知。

我的代码:

    public class GCMIntentService extends GCMBaseIntentService {

----------------------- other code ----------------------------------------

    @Override
        protected void onMessage(Context context, Intent intent) {
            Log.d(TAG, "onMessage : " + String.valueOf(intent));

            // This is how to get values from the push message (data)
            String payload = intent.getExtras().getString("payload");
            String message = "";
            String messageID;

            if (payload.contains("{")) {
                try {
                    JSONObject jsonArray = new JSONObject(payload);

                    message = jsonArray.get("Msg").toString();
                    messageID = jsonArray.get("MessageID").toString();

                    GA_Handler.sendEvent("Popup_Push", String.format("Push message %s", messageID));

                } catch (Exception ex) {
                    // Do nothing
                }
            } else {
                message = payload;
            }

            // special intent with action we make up
            Intent pushReceivedIntent = new Intent(ACTION_PUSH); 
            // place old extras in new intent
            pushReceivedIntent.putExtras(intent.getExtras());
            // find out if there any BroadcastReceivers waiting for this intent
            if (context.getPackageManager().queryBroadcastReceivers(pushReceivedIntent, 0).size() > 0) {
                // We got at least 1 Receiver, send the intent
                context.sendBroadcast(pushReceivedIntent);
            } else {
                // There are no receivers, show PushNotification as Notification
                // long timestamp = intent.getLongExtra("timestamp", -1);
                NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                Notification note = new Notification(R.drawable.ic_launcher, "MYAPP", System.currentTimeMillis());
                Intent notificationIntent = new Intent(context, SplashActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
                note.setLatestEventInfo(context, "MYAPP", message, pendingIntent);
                note.number = count++;
                note.defaults |= Notification.DEFAULT_SOUND;
                note.defaults |= Notification.DEFAULT_VIBRATE;
                note.defaults |= Notification.DEFAULT_LIGHTS;
                note.flags |= Notification.FLAG_AUTO_CANCEL;

                notificationManager.notify(0, note);
            }
        }
----------------------- other code ----------------------------------------    }

在我的 BaseActivity 中:

@Override
    protected void onResume() {
        super.onResume();

        //register as BroadcastReceiver for Push Action
        IntentFilter filter = new IntentFilter();
        filter.addAction(GCMIntentService.ACTION_PUSH);

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
              DialogFragmentUtils.getNotification("Notification", "Notification");
            }
          };
          registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        FragmentManager fm = getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }

        //unregister broadcast receiver
        unregisterReceiver(mReceiver);
    }

我总是收到通知。
当我调试 context.getPackageManager().queryBroadcastReceivers(pushReceivedIntent, 0).size() 时总是等于 0。

谁能告诉我我做错了什么?

最佳答案

似乎 PackageManager.queryBroadcastReceivers() 会返回应用程序 list 中声明的​​与给定 Intent 匹配的所有接收器。

但是请注意,这不包括使用 Context.registerReceiver() 注册的接收器;目前无法获取有关这些的信息。

您可以在 onReceive() 中使用以下代码来确定应用程序/Activity 是否正在运行

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClass().getSimpleName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equalsIgnoreCase("your.package.name")){
    //Activity in foreground, broadcast intent
} 
else{
    //Activity Not Running
    //Generate Notification
}

关于android - 当应用程序以不同方式打开/关闭时显示推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16394666/

相关文章:

android - 使用 ActionBarCompat 和 requestWindowFeature

android - 在 Android 中以编程方式执行 shell 命令

javascript - Chrome 上的 Firebase 云消息传递未经授权错误 401

android - Pushwoosh/GCM - Android - 不接收消息

java - 我应该在 GoogleCloudMessaging 实例上显式调用 close 方法吗?

android - 键盘背景状态

Android,构建成功,但 apk 构建(后续运行)失败

ios - 代号一推送通知未在 iOS 10 上注册

ios - Ionic 3.x : Push notification on iOS not working (works on Android? ) Ionic Native 插件推送

android - GCM 演示不会在服务器和应用重启时接受消息