[Android][解析] 推送通知 - 在某些 activity 中拦截应用程序内部的通知并执行某些方法

[Android][Parse] Push notifications - intercept notification inside the app when being in some activity and execute some method

我已经在我的 Android 应用程序上实现了 Parse Push Notifications 服务,并将这些行添加到 AndroidManifest.xml:

<service android:name="com.parse.PushService" />
    <receiver android:name="com.parse.ParseBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
    <receiver android:name="com.parse.ParsePushBroadcastReceiver"
        android:exported="false">
        <intent-filter>
            <action android:name="com.parse.push.intent.RECEIVE" />
            <action android:name="com.parse.push.intent.DELETE" />
            <action android:name="com.parse.push.intent.OPEN" />
        </intent-filter>
    </receiver>
    <receiver android:name="com.parse.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="my.package.name" />
        </intent-filter>
    </receiver>

推送通知运行良好,当用户通过按下推送通知警报启动应用程序时,足够的 activity 启动。我发送的推送通知具有以下形式:

alert: "message to show",
type: "type_1",
data: "some_data"

现在,我不知道该怎么做,只有在具体 activity(例如 MyActivity)时,我想 "intercept" 推送通知具有类型标签的某些值(例如那些 "type_1")并在 activity 上执行一个方法(例如 refreshView)以启动异步任务以从服务器检索数据并刷新根据它的一些视觉元素。如果用户在另一个activity(不是MyActivity),推送通知应该可以正常接收,不会被拦截。

我尝试实现广播接收器但没有成功。我怎样才能做到这一点?

谢谢。

您可以尝试动态注册和取消注册适当的 Receiver 通知。 因此,例如在 activity 中你想要 "listening" 尝试:

private BroadcastReceiver receiver; // Maybe is a good idea to subclass ParsePushBroadcastreceiver...
IntentFilter filter;

@Override
public void onCreate(Bundle savedInstanceState){   
  filter = new IntentFilter();
  filter.addAction("SOME_ACTION");

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      // Received!
    }
  }
  registerReceiver(receiver, filter); // Actually don't know if it is necessary since i register the receiver in onResume() also...
}

@Override
protected void onResume() {
     super.onResume();
     registerReceiver(mReciever, mIntentFilter); // Listen when activity goes in foreground
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receive); // Don't listen when activity is not in foreground
}

@Override
protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(receiver); // Avoid LEAKED RECEIVER!
}

至于现在我没有尝试这个解决方案,但是如果你选择这个,你不应该使用清单注册接收器,因为它不再依赖于应用程序生命周期(即接收器运行无论状态如何你的申请)。

如果您不想保留 android 清单注册接收器,也许一个好主意是在监听 activity 进入前台时将静态布尔变量设置为 true,而当监听进入前台时设置为 false它熄灭,然后接收器可以根据该布尔值执行操作。

总之,看看Context.registerreceiver() and BroadcastReceiver

干杯!