Android - BroadcastReceiver 中的 Intent 丢失了字符串

Android - Intent in BroadcastReceiver lost String

我想使用 BroadcastReceiver 发送带有特定字符串的通知。这是我在 MainActivity 中的函数:`

private void createAlarm (int i) throws ParseException {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("name", names.get(i));

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
                (int) timeInMillis / 1000),
                intent,
                PendingIntent.FLAG_ONE_SHOT
        );

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
        }
    }

广播接收者代码:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String name = intent.getExtras().getString("name", "deafultValue");

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Intent notificationIntent = new Intent(context, MainActivity.class);
            TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
            taskStackBuilder.addNextIntentWithParentStack(notificationIntent);
            PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(50, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "EventStartChannel")
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setContentTitle(name)
                    .setContentText(name)
                    .setColor(Color.argb(255, 255, 0, 0))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            notificationManager.notify((int) System.currentTimeMillis() / 1000, builder.build());
        }
    }
}

清单代码:

        <receiver android:name=".OtherClasses.AlarmReceiver"
            android:enabled="true"
            android:exported="false" >

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.SEND" />
            </intent-filter>

        </receiver>

但有时,当闹钟设置在一天或更长时间后,onReceive 中的 extras 为空并且 name 获得默认值。我试过在 extras 中用 bundle 传递字符串,然后是同样的问题。

发送

改变这个:

intent.putExtra("name", names.get(i));

收件人:

intent.putExtra(android.content.Intent.EXTRA_TEXT, names.get(i));

得到

改变这个:

String name = intent.getExtras().getString("name", "deafultValue");

收件人:

String name = intent.getStringExtra(android.content.Intent.EXTRA_TEXT);