我的应用中有MainActivity和WorkActivity。从MainActivity开始的WorkActivity:
Intent intent = new Intent(view.getContext(), WorkActivity.class);
intent.putExtra("intArray", intArray);
startActivity(intent);
在WorkActivity中,我读取intArray参数并使用通知启动前台服务:
protected void onCreate(Bundle savedInstanceState) {
int[] intArray = getIntent().getIntArrayExtra("intArray");
Intent intent = new Intent(this, MyService.class);
intent.putExtra("intArray", intArray);
startService(intent);
}
服务通知:
Intent newIntent = new Intent(this, WorkActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, newIntent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("title)
.setContentIntent(pIntent)
.setContentText("text");
Notification notification;
notification = builder.build();
startForeground(1, notification);
现在,当我关闭我的应用并点击通知时发生错误,因为WorkActivity无法获取
getIntent().getIntArrayExtra("intArray");
应该由MainActivity传递。 如何解决这个问题?
日志:
java.lang.RuntimeException: Unable to start service com.test.MyService@9051e18 with Intent { cmp=com.test/.MyService (has extras) }: java.lang.NullPointerException: Attempt to read from null array
发生错误,因为WorkActivity.getIntent()。getIntArrayExtra(“intArray”)为null。 活动将其发送到服务行:
intent.putExtra("intArray", intArray);
startService(intent);
在服务中我需要从intArray中获取一些数字,如intArray [0],但intArray为null
答案 0 :(得分:0)
当您转到通知栏并选择通知时,会启动WorkActivity
的新实例。 WorkActivity
的此实例不是从您的MainActivity
开始,而是通过通知启动,而您在通知中添加的Intent
没有额外的intArray
。
基本上,您需要将putExtra()
intArray
调用添加到此代码中:
Intent newIntent = new Intent(this, WorkActivity.class);
// HERE YOU NEED TO CALL newIntent.putExtra("intArray", intArray);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, newIntent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("title)
.setContentIntent(pIntent)
.setContentText("text");