【问题标题】:Show push notifications when application open/closed in different way当应用程序以不同方式打开/关闭时显示推送通知
【发布时间】:2013-05-06 08:14:46
【问题描述】:

在我的应用中,我有几个从一个 BaseActivity 继承的活动。
我的应用程序收到带有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。

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    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
    }
    

    【讨论】:

    • 这只是为了获取其他信息,我们必须在清单文件中使用以下权限才能获取正在运行的任务信息。
    【解决方案2】:

    您可以使用此代码检查应用程序是在后台还是前台:

        public String isApplicationSentToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return "false";
            }
        }
    
        return "true";
    }
    

    如果返回“true”,则显示通知,否则显示对话框。

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

    为此,请不要在 notify() 中传递 0。而是传递“Calendar.getInstance().getTimeInMillis()”值。这将显示所有基于时间的通知。

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2018-03-21
      • 2021-06-25
      相关资源
      最近更新 更多