我遇到了一个问题,我试图设置一个Android通知,但当我计划一个额外的意图时,额外的结果是空的.

我创建Intent和pendingIntent的代码如下所示:

 EditText alertVacName = findViewById(R.id.editVacName);
            EditText alertHotName = findViewById(R.id.editHotName);
            EditText alertVacStartDate = findViewById(R.id.editVacStartDate);
            EditText alertVacEndDate = findViewById(R.id.editVacEndDate);



            String VacName = alertVacName.getText().toString();
            String AlertStartDate = alertVacStartDate.getText().toString();
            String AlertEndDate = alertVacEndDate.getText().toString();
            String AlertHotName = alertHotName.getText().toString();



            long trigger = DateConverter.toDate(sVacStartDate).getTime();
            Intent intent = new Intent(VacationDetails.this, Vacation_Alert.class);
            intent.putExtra("mainText", (VacName +" Starts Today!"));
            intent.putExtra("Details", ("Start Date: " + AlertStartDate + "\n" +
                                              "End Date: " + AlertEndDate + "\n" +
                                              "Hotel: " + AlertHotName));
            Log.d("Checking Intent Content:", intent.getStringExtra("Details"));
            PendingIntent sender = PendingIntent.getBroadcast(VacationDetails.this, ++MainActivity.numAlert, intent, PendingIntent.FLAG_IMMUTABLE);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, sender);
            Log.d("Checking Intent Content After Schedule:", intent.getStringExtra("Details"));

我的广播接收器如下所示(我还在这里创建了通知通道):

public class Vacation_Alert extends BroadcastReceiver {
    String channel_id = "test";
    static int noteID;

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

        // Make sure to check if the extras are present before retrieving them
        if (intent != null && intent.getExtras() != null) {
            String title = intent.getStringExtra("mainText");
            String message = intent.getStringExtra("Details");

            // Debugging statement to check the value of "Details"
            Log.d("Vacation_Alert", "Received message: " + message);

            // Ensure that message is not null; use an empty string if it is
            if (message == null) {
                message = "";
            }

            Notification notification = new NotificationCompat.Builder(context, channel_id)
                    .setSmallIcon(R.drawable.vacation)
                    .setContentTitle("Vacation/Excursion Alert!")
                    .setContentText(title)
                    .setContentInfo(message)  // Use the retrieved message
                    .build();

            // Commented out the Toast for now, as it was causing issues
            // Toast.makeText(context, message, Toast.LENGTH_LONG).show();

            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(noteID++, notification);
        } else {
            // Handle the case where the intent or extras are null
            Log.e("Vacation_Alert", "Received null intent or extras");
        }
    }



    private void createNotificationChannel(Context context, String CHANNEL_ID) {
        CharSequence name = "Vacation Alert";
        String description = "Alert for Vacations";

        int importance = NotificationManager.IMPORTANCE_DEFAULT;

        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

我知道这些附加内容被分配给了意图,因为它们会出现在我安排闹钟时设置的日志(log)中.通知在正确的时间触发,但getStringExtra方法在被广播接收器接收后返回NULL.LogCAT数据如下所示:

2023-11-30 20:44:05.779 22344-22389 ProfileInstaller        android.reserver.d308project         D  Installing profile for android.reserver.d308project
2023-11-30 20:44:08.478 22344-22365 EGL_emulation           android.reserver.d308project         D  app_time_stats: avg=206.59ms min=1.40ms max=2407.80ms count=13
2023-11-30 20:44:08.634 22344-22365 OpenGLRenderer          android.reserver.d308project         E  Unable to match the desired swap behavior.
2023-11-30 20:44:09.663 22344-22344 Checking I...t Content: android.reserver.d308project         D  Start Date: 2023-11-30
                                                                                                    End Date: 2023-12-05
                                                                                                    Hotel: Text
2023-11-30 20:44:09.664 22344-22344 Compatibil...geReporter android.reserver.d308project         D  Compat change id reported: 160794467; UID 10190; state: ENABLED
2023-11-30 20:44:09.667 22344-22344 Checking I... Schedule: android.reserver.d308project         D  Start Date: 2023-11-30
                                                                                                    End Date: 2023-12-05
                                                                                                    Hotel: Text
2023-11-30 20:44:09.738 22344-22365 EGL_emulation           android.reserver.d308project         D  app_time_stats: avg=52.68ms min=1.84ms max=558.02ms count=18
2023-11-30 20:44:09.807 22344-22365 EGL_emulation           android.reserver.d308project         D  app_time_stats: avg=17.40ms min=1.39ms max=403.42ms count=32
2023-11-30 20:44:09.989 22344-22344 WindowOnBackDispatcher  android.reserver.d308project         W  sendCancelIfRunning: isInProgress=falsecallback=android.view.ViewRootImpl$$ExternalSyntheticLambda17@956e043
2023-11-30 20:44:10.008 22344-22365 OpenGLRenderer          android.reserver.d308project         D  endAllActiveAnimators on 0x7daa5f9caa00 (MenuPopupWindow$MenuDropDownListView) with handle 0x7da94f98c4f0
2023-11-30 20:44:14.671 22344-22344 Vacation_Alert          android.reserver.d308project         D  Received message: null
2023-11-30 20:44:16.380 22344-22365 EGL_emulation           android.reserver.d308project         D  app_time_stats: avg=1643.25ms min=31.65ms max=6418.44ms count=4

你觉得我哪里做错了吗?这是我第一次涉足android开发,所以请原谅任何多余或笨重的代码.

推荐答案

您需要更改此设置:

PendingIntent sender = PendingIntent.getBroadcast(VacationDetails.this,
    ++MainActivity.numAlert, intent, PendingIntent.FLAG_IMMUTABLE);

对此:

PendingIntent sender = PendingIntent.getBroadcast(VacationDetails.this,
    ++MainActivity.numAlert, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

添加PendingIntent.FLAG_UPDATE_CURRENT确保新的Intent"extra"被复制到PendingIntent的目标中.

Android相关问答推荐

如何使用单个代码库使用不同的firebase项目创建多个应用程序ID apk

房间@嵌入式VS一对一关系

在Jetpack Compose中,我可以配置动画以恒定的速度而不是恒定的时间运行吗?

如何显示具体的商品数量?

SDK 33 的问题 - 面向 S+(版本 31 及更高版本)要求在创建 PendingIntent 时指定 FLAG_IMMUTABLE 或 FLAG_MUTABLE 之一

使用不同的gradle文件导入外部库

有没有办法让协程通道在接收时遵循特定的顺序而不是先进先出

如何避免多次调用 Jetpack Compose 的 onClick 回调

Android AGP 8 + Gradle 8 + Kotlin 1.8 导致 Kapt 出错

在 Material 3 TopAppBar 代码的哪个位置定义了填充?

从 HiltViewModel @Injection 访问 Application()

Electric Eel 后 Gradle 项目同步失败 | 2022.1.1更新

如何在没有人窃取令牌的情况下使用我的移动应用程序中的 API

无法 HEAD 'https://jcenter.bintray.com/com/facebook/react/react-native/maven-metadata.xml'

获取模板向导配方类 Intellij 中的应用程序包名称

在 jetpack compose 中使用 viewmodel 的最佳实践

如何在 Jetpack Compose 中填充矢量图像的背景?

Android Studio (Kotlin):无法启动活动

如何在 flow.stateIn() 之后从流中的另一个函数发出emits ?

Android TTS 在屏幕关闭一段时间后停止朗读