Кнопки уведомлений: onReceive не вызывается - PullRequest
0 голосов
/ 08 февраля 2020

Я пытался реализовать уведомление с помощью кнопки и приемника вещания. Однако, когда я нажимаю кнопку, функция onReceive моего широковещательного приемника никогда не вызывается. Я пробовал это как на эмуляторе, так и на реальном устройстве. Кнопка нажата, но функция не вызывается.

Я искал по inte rnet и прочитал много примеров, но не смог найти причину. Я пробовал как зарегистрировать получателя через манифест android, так и в коде.

У кого-нибудь есть идея?

Вот мой код:

Манифест:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.karina.testanwendungso"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="21"
        android:targetSdkVersion="29" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo" >
        <activity
            android:name="de.karina.testanwendungso.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="de.karina.testanwendungso.MediaButtonBroadcastReceiver"/>
    </application>

</manifest>

NotificationBroadcastReceiver:

public class NotificationBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("##################### Testanwendung in onReceive");
        Toast.makeText(context, "in onReceive", Toast.LENGTH_SHORT).show();
   }
}

MainActivity:

public class MainActivity extends Activity {

    String CHANNEL_ID = "KarinasTestanwendungso";
    int NOTIFICATION_ID = 101;
    final static private String ACTION_BACK = "de.karina.testanwendungso.actionback";

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

        buildNotification();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @SuppressLint("NewApi")
    private void buildNotification() {

        Intent backIntent = new Intent(this, NotificationBroadcastReceiver.class);
        backIntent.setAction(ACTION_BACK);
        PendingIntent backPendingIntent = PendingIntent.getBroadcast(this,  0 , backIntent, 0); 

        NotificationManager notificationManager = null;
        Notification.Builder builder = null;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this).setPriority(Notification.PRIORITY_DEFAULT);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channelname", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel-Beschreibung");

            notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);

            builder = new Notification.Builder(this,  CHANNEL_ID);
        }

        builder.setSmallIcon(R.drawable.ic_actionbar)
        .setContentTitle("Titel")
        .setContentText("Text")
        .addAction(R.drawable.ic_action_next, "back", backPendingIntent)
        ;

        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }

        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }
}
...