通过广播接收器和rxJava2进行通知的问题

时间:2018-11-04 11:00:06

标签: android notifications broadcastreceiver rx-java2 dagger-2

我在广播接收器中遇到了通知问题。

这里的班级:

public class JokeAlarmReceiver extends BroadcastReceiver {

CompositeDisposable compositeDisposable = new CompositeDisposable();

public static final String NOTIFICATION_CHANNEL_ID = "Channel Joke ID";
public static final String NOTIFICATION_CHANNEL_NAME = "Channel";
public static final int NOTIFICATION_ID = 123;

@Inject
DataManager dataManager;


@Override
public void onReceive(Context context, Intent intent) {
    ((JokeApplication)context.getApplicationContext()).getAppComponent()
            .plus(new JokeAlarmReceiverModule(context))
            .inject(this);


    getJokesToNotification();
    createNotification(context);

}

public void createNotification(Context context) {

        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_mood_black_24dp)
                .setContentTitle("Smile Reminder :)")
                .setContentText(dataManager.getJokeForNotification())
                .setStyle(new NotificationCompat.BigTextStyle())
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT);

            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(NOTIFICATION_ID, mBuilder.build());


    }



public void getJokesToNotification(){

    compositeDisposable.add(dataManager.getJokes()
           .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    randomJokes -> {
                        // onNext
                            dataManager.setJokeForNotification(randomJokes.getSetup(),randomJokes.getPunchline());
                        Log.d("WORKING","1st");
                        },
                    throwable -> {
                        // onError
                    },
                    () -> {
                        // onCompleted
                    })
    );
}

简而言之,它是如何工作的...我将方法与rxjava一起使用来调用API,这应该给我对象RandomJoke,从中我将文本分为两部分。我注入要存储文本的dataManager。然后,我将此文本用作通知文本。我想让通知显示重复,即使我的应用程序关闭也是如此。当应用程序仍在工作时,问题就很好了,但是当我关闭它时……拳头通知我得到的是空值,而文本和第二个以及其余的通知工作正常。谁能告诉我做错了什么? 广播是通过清单注册的,我使用API​​ 25在模拟器上测试了所有内容

0 个答案:

没有答案