android推送消息点击事件,【Android开发那点破事】消息推送BroadcastReceiver,点击通知打开两次Activity问题...

Android开发:BroadcastReceiver处理Push推送及通知点击事件
在Android开发中,BroadcastReceiver常用于接收Push推送消息。当用户点击通知时,需要在BroadcastReceiver中添加逻辑,如启动MainActivity。代码示例展示了如何在JPushReceiver中处理ACTION_NOTIFICATION_OPENED事件,避免因缺少FLAG_ACTIVITY_NEW_TASK导致的异常,确保每次打开推送只会启动一个Activity。

Android开发中,通常会使用BroadcastReceiver来接受Push推送消息。当APP收到推送通知时,我们需要在通知的点击事件中加入自己的逻辑。比如跳转到MainActivity。

比如下面的代码(注意红色部分):

public void onReceive(Context context, Intent intent) {

Bundle bundle = intent.getExtras();

if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {

String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);

Log.d(TAG, "[JPushReceiver] 接收Registration Id : " + regId);

//send the Registration Id to your server...

} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {

Log.d(TAG, "[JPushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));

} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {

Log.d(TAG, "[JPushReceiver] 接收到推送下来的通知");

int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

Log.d(TAG, "[JPushReceiver] 接收到推送下来的通知的ID: " + notifactionId);

} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {

Log.d(TAG, "[JPushReceiver] 用户点击打开了通知");

JPushInterface.reportNotificationOpened(context, bundle.getString(JPushInterface.EXTRA_MSG_ID));

// 打开自定义的Activity

Intent i = new Intent(context, MainTabActivity.class);

i.putExtras(bundle);

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(i);

} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {

Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));

//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

} else {

Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());

}

}

使用Activity以外的content来startActivity,必须指定为Intent.FLAG_ACTIVITY_NEW_TASK。

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

我们可以尝试下使用Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT,会抛出以下异常:

ERROR/AndroidRuntime(7557): java.lang.RuntimeException: Unable to start receiver com.wcc.Wakeup: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

这样每次打开推送,就不会出现2个activity的情况了。

好了今天这个破事就到这里,其实android开发就这么点破事。关于其他破事,见专栏:

更多Android开发的破事,请看专栏:《Android开发那点破事》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值