【问题标题】:Cancel different onGoing notifications取消不同的持续通知
【发布时间】:2016-03-02 10:51:06
【问题描述】:

我有不同的持续通知。当按下 addAction() 按钮时,会调用 BroadcastReceiver 并清除我的通知。问题是 addAction() 总是传递最后添加的通知的 id,而不是你按下的那个:

这里是添加通知的方法:

    public void pushNotification(View v){
      String text = editText.getText().toString().trim();
      editText.setText("");
      int millis = (int) (System.currentTimeMillis() % Integer.MAX_VALUE);
      Intent notificationIntent = new Intent(mContext, NotificationReceiver.class);
      notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      notificationIntent.putExtra("id", millis);
      PendingIntent pIntent = PendingIntent.getBroadcast(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

      NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
      notification.setContentTitle("");
      notification.setContentText(text);
      notification.setSmallIcon(R.mipmap.ic_launcher);
      notification.setOngoing(true);
      notification.addAction(R.mipmap.ic_launcher, "Dismiss", pIntent);

      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      notificationManager.notify(millis, notification.build());
    }

接收者:

public class NotificationReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent){
      NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      manager.cancel(intent.getIntExtra("id", 0));
  }
}

清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="PACKAGE_NAME">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".NotificationReceiver" />
</application>

【问题讨论】:

    标签: java android notifications


    【解决方案1】:

    我找到了解决方案,只需将FLAG_ONE_SHOT 添加到您的待处理意图中,现在所有extras 都会有所不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多