Android-意图在BroadcastReceiver丢失字符串



我想使用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);
}
}

BroadcastReceiver代码:

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中的附加值为空,名称会变为无效值。我试过在额外的程序中用捆绑包传递字符串,但也遇到了同样的问题。

发送

更改此项:

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);

最新更新