我试图通过以下代码传递一些数据来启动服务:
Intent countDownTimerIntent = new Intent(getActivity(), CountDownTimerService.class);
Bundle bundle = new Bundle();
bundle.putLong(CountDownTimerService.DURATION, ((Test) mcqDataSet).getDuration());
countDownTimerIntent.putExtras(bundle);
getContext().startService(countDownTimerIntent );
现在,当我尝试从Intent接收束数据时,它显示某些数据存在于bundle中,但其映射为null
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
final long duration = bundle.getLong(DURATION, 0l);
答案 0 :(得分:1)
经过多次努力,我发现onStartCommand中的返回类型应为 START_REDELIVER_INTENT 。这是因为很多时候意图迷失并且没有传递。因此,此返回类型会强制它在需要获取数据时重新传递它。代码如下:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
if (bundle != null)
final long duration = bundle.getLong(DURATION, 0l);
return START_REDELIVER_INTENT;
}
答案 1 :(得分:0)
您可以使用以下代码通过数据发送意图。
Intent countDownTimerIntent = new Intent(getActivity(), CountDownTimerService.class);
countDownTimerIntent.putExtra(CountDownTimerService.DURATION, ((Test) mcqDataSet).getDuration());
getContext().startService(countDownTimerIntent );