首页 文章

在Service中的onStartCommand中,意图中的Bundle in intent为null

提问于
浏览
0

我试图通过以下代码传递一些数据来启动服务:

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

以下是bundle看起来如何调试
the debug mMap values here

2 回答

  • 1

    您可以使用以下代码发送数据意图 .

    Intent countDownTimerIntent = new Intent(getActivity(), CountDownTimerService.class);
        countDownTimerIntent.putExtra(CountDownTimerService.DURATION, ((Test) mcqDataSet).getDuration());
        getContext().startService(countDownTimerIntent );
    
  • 0

    经过很多努力,我发现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;
    }
    

相关问题