Java 如果向服务传递多个意图,如何从意图中获取捆绑包
我正在将意图从应用程序中的两个不同位置传递到服务。一个intent有一个bundle,我想从中提取数据,但当我尝试运行getIntent().getExtras()方法时,我得到了NPE 编辑: 在一类中:Java 如果向服务传递多个意图,如何从意图中获取捆绑包,java,android,Java,Android,我正在将意图从应用程序中的两个不同位置传递到服务。一个intent有一个bundle,我想从中提取数据,但当我尝试运行getIntent().getExtras()方法时,我得到了NPE 编辑: 在一类中: basket.putString("KEY1", id[i]); basket.putString("KEY2", message[i]); bas
basket.putString("KEY1", id[i]);
basket.putString("KEY2", message[i]);
basket.putString("KEY3", timeFormat[i]);
passNotiData = new Intent(getActivity(),
CheckService.class);
passNotiData.putExtras(basket);
startService(passNotiData);
在另一节课上
Intent myIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, myIntent, 0);
context.startService(myIntent);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000, PERIOD, pi);
在服务舱
Bundle gotBasket = intent.getExtras();
oldId = gotBasket.getString("KEY1");
oldTime = gotBasket.getString("KEY3");
我正在从两个班传递意图。在这两个意图中,只有一个意图具有约束力。如何筛选该意图?您只需检查该意图的null操作。类似intent.getExtras()!=nullYes这将停止错误,但我如何将这些字符串放入我的服务中?如果有捆绑包,那么您可以从上面获得。如果要将字符串传递给服务,则需要将bundle添加到intent并再次调用startService(intent)方法。您说过一个intent有bundle,另一个没有。因此,必须先检查空指针条件,然后才能解析它。
//start service from activity or any place
Intent intent = new Intent(this, MyService.class);
Bundle bundle = new Bundle();
bundle.putString("TEST", "test got it.");
intent.putExtras(bundle);
startService(intent);
//In service class declare override method of service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (intent != null && intent.getExtras() != null) {
String str = intent.getExtras().getString("TEST");
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG)
.show();
}
return START_NOT_STICKY;
}