Android通知栏RemoteInput调用getResultsFromIntent返回null问题咨询
RemoteInput.getResultsFromIntent() 返回null的常见原因及解决方案
核心问题原因
- PendingIntent使用了
FLAG_IMMUTABLE标识:这是最常见的问题,不可变的PendingIntent会禁止系统向其中附加用户输入的RemoteInput结果,导致后续读取时返回null。Android 12及以上版本要求涉及外部输入修改的PendingIntent必须使用可变标识。 - RemoteInput包导入不匹配:如果你使用的是
androidx.core.app.NotificationCompat构建通知,必须配套使用androidx.core.app.RemoteInput,如果错误导入了平台原生的android.app.RemoteInput,会导致结果解析失败返回null。 - 字符串对比逻辑错误:Service中判断Action使用了
==比较字符串,正确应该使用equals()方法,极端情况下会因为Action字符串引用不一致导致逻辑不执行,容易误以为是getResultsFromIntent返回null。 - 同一PendingIntent被重复复用:如果之前已经用过相同requestCode(你的代码中是20)的不可变PendingIntent,系统会复用旧的实例,就算你修改了Flag也不会生效,需要卸载应用重装或者修改requestCode测试。
修正代码示例
Activity端PendingIntent修改
将原不可变Flag替换为可变Flag,兼容低版本系统:
PendingIntent pIntentMenu; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { pIntentMenu = PendingIntent.getService(getApplicationContext(),20,intentMenu,PendingIntent.FLAG_MUTABLE); } else { pIntentMenu = PendingIntent.getService(getApplicationContext(),20,intentMenu,PendingIntent.FLAG_UPDATE_CURRENT); }
Service端逻辑优化
修正字符串对比逻辑,增加空判断避免崩溃:
public int onStartCommand(Intent intent, int flags, int startId) { if("personalACTION".equals(intent.getAction())) { Bundle keys = RemoteInput.getResultsFromIntent(intent); if(keys != null) { CharSequence text = keys.getCharSequence(FV.REMOTE_INPUT_KEY); Toast.makeText(this, "Reply with"+text, Toast.LENGTH_SHORT).show(); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); Notification notificationRemoteInput = new NotificationCompat.Builder(this,FV.CHANNEL_TEST) .setSmallIcon(R.drawable.linterna) .setContentTitle("Conversation with Javier") .setContentText("Javier: Hi! How are you? \n Me:"+text) .setAutoCancel(true) .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.foto1)).build(); notificationManager.notify(FV.NOTIFICATION_CONVERSATION,notificationRemoteInput); } } return super.onStartCommand(intent, flags, startId); }
内容的提问来源于stack exchange,提问作者Jamani
相关产品推荐
相关产品推荐

