我在Android应用程序的主要活动中有一个子类BroadCastReceiver,用于处理GCM进入时更改GUI。所有这些都可以正常工作。
有一点不起作用的是,如果这个被调用,那么用户就可以在他的设备上打开我的应用程序了,因此我想清除我输入此通知GCM的通知中心的通知。如果我将cancelAll()和cancel(int)行放入我的GCMIntentService,那么它会解除通知,但我不能保留它,因为我只想在用户打开我的应用程序时忽略此通知。我使用了cancel()和cancelAll()来确保我没有以某种方式从IntentService传递错误的通知ID(我已经验证它是正确的)。
问题在于没有错误,通知中心的通知根本不会消失。我已经验证了这个方法被调用,因为我在logcat中获取了日志条目。
我引用了之前的答案,但由于某些原因,它在我的实施中无效:Starting and stopping a notification from broadcast receiver
我的主要活动中的代码:
private class NotificationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Push", "Received Push Notification!");
//Now that the user has opened the app, cancel the notification in the notification center if it is still there
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final int NOTIFICATION_ID = intent.getIntExtra("notificationId",0);
Log.v("NOTIFICATION_ID",Integer.toString(NOTIFICATION_ID));
mNotificationManager.cancel(NOTIFICATION_ID);
mNotificationManager.cancelAll();
Log.v("Canceled Notifs","Canceled");
}
}
任何想法为什么?
答案 0 :(得分:2)
一个可能更好的选择是,不是在应用程序打开时发布通知,而是首先检测应用程序是否可见,如果是,则不显示通知。您可以使用Intent
广播或事件总线(如EventBus或Otto)来执行此操作。
示例:
public class GCMReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// this is your receiver after gcm has been received
Intent appOpenCheck = new Intent("com.example.IS_APP_OPEN");
// put extras about your notification here...
context.sendOrderedBroadcast(appOpenCheck);
}
}
public class AppNotOpenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// this is your receiver that will be hit if the app isn't open
// post your notification to the NotificationManager
}
}
然后,在AndroidManifext.xml
:
<receiver
android:name=".AppNotOpenReceiver">
<intent-filter>
<action android:name="com.example.IS_APP_OPEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
最后,在Activity
:
BroadcastReceiver appOpenAlert = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
abortBroadcast(); // prevents notification from going further
// this is your receiver that will be hit if the app is open
// update your ui
}
}
@Override
public void onStart() {
super.onStart();
IntentFilter notificationReceived = new IntentFilter();
notificationReceived.addAction("com.example.IS_APP_OPEN");
notificationReceived.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(appOpenAlert, notificationReceived);
}
@Override
public void onStop() {
unregisterReceiver(appOpenAlert);
super.onStop();
}