Уведомление не отменяется в Android 10 - PullRequest
2 голосов
/ 28 апреля 2020

Проблема: я хочу отменить уведомление, когда я непосредственно отвечаю на это уведомление. Он работает в Android N, но не работает в Android 10.

Мой код выглядит следующим образом:

MainActivity. java

    public class MainActivity extends AppCompatActivity {

    public static final int NOTIFICATION_ID = 1256;
    public static final String CHANNEL_1_ID = "channel1";

    private Button btnDisplayNotification;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createNotificationChannel();

        btnDisplayNotification = findViewById(R.id.btnDisplayNotification);

        btnDisplayNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                displayNotification(MainActivity.this);
            }
        });
    }

    private void createNotificationChannel() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel channel1 = new NotificationChannel(
                    CHANNEL_1_ID,
                    "Channel 1",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
        }
    }

    public static void displayNotification(Context context) {

        Intent replyIntent;
        PendingIntent replyPendingIntent = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            replyIntent = new Intent(context, ReceiverIntentService.class);
            replyPendingIntent = PendingIntent.getService(context, 0, replyIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        } else {

            replyIntent = new Intent(context, ReplyActivity.class);
            replyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            replyPendingIntent = PendingIntent.getActivity(context, 0, replyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        RemoteInput remoteInput = new RemoteInput.Builder("key_text_reply")
                .setLabel("Your answer...")
                .build();

        NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
                R.drawable.ic_reply,
                "Reply", replyPendingIntent)
                .addRemoteInput(remoteInput)
                .build();

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_1_ID);
        notificationBuilder.setSmallIcon(R.drawable.ic_launcher_background)
                .addAction(replyAction)
                .setContentTitle("Hot Jobs")
                .setContentText("Check out hot jobs based on your skills")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify("NOTI_TAG", NOTIFICATION_ID, notificationBuilder.build());
    }
}

ReceiverIntentService. java

    public class ReceiverIntentService extends IntentService {

    public ReceiverIntentService() {
        super("blah");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);

        if (remoteInput != null) {

            CharSequence replyText = remoteInput.getCharSequence("key_text_reply");

            Log.e("NotiReply", "IS Reply is: " + replyText);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
            if (notificationManager != null) {
                stopForeground( true );
                notificationManager.cancel("NOTI_TAG", NOTIFICATION_ID);
            }
        }
    }
}

AndroidManifest. xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="web.b.notificationreplydemo2">

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_notifications_black_24dp"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".ReplyActivity"></activity>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver android:name=".DirectReplyReceiver" />

        <service
            android:name=".ReceiverIntentService"
            android:exported="false" />
    </application>

</manifest>

В приведенном выше коде , Я пытался использовать BroadcastReceiver , но такая же проблема возникает.

Я прилагаю скриншот того, чего я хочу достичь. Это ниже.

enter image description here

ОБНОВЛЕНИЕ 29 АПРЕЛЯ 2020

Я запускаю тот же проект на ANDROID Эмуляторы 8 и ANDROID 9. Это работало, как и предполагалось, на ANDROID 8, но та же проблема на ANDROID 9 (не отменяет уведомление после ответа).

Я нашел тот же вопрос здесь.

1 Ответ

0 голосов
/ 05 мая 2020

Я бы порекомендовал вам сделать следующее:

  1. проверить, называется ли метод onHandleIntent ваших служб
  2. , проверить, не является ли remoteInput ноль *, 1007 *
  3. . если notificationManager не равно нулю
  4. попытаться отменить уведомление по идентификатору без тега
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...