【问题标题】:Handle situation when Intent is null during onHandleIntentonHandleIntent 期间 Intent 为空时的处理情况
【发布时间】:2018-03-21 09:16:22
【问题描述】:

我有以下IntentService

public class NotificationIntentService extends IntentService {
    public NotificationIntentService() {
        super("NotificationIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        boolean retainStockPriceAlert = intent.getBooleanExtra(RETAIN_STOCK_PRICE_ALERT, true);
        ...
    }
}

我使用以下代码启动IntentService

Intent intent = new Intent(this, NotificationIntentService.class);
intent.putExtra(NotificationIntentService.RETAIN_STOCK_PRICE_ALERT, retainStockPriceAlert);
startService(intent);

然而,令我惊讶的是,一些用户在onHandleIntent 期间得到了空的Intent。因此,发生了 NPE。

来自文档https://developer.android.com/reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)

Intent:传递给 startService(Intent) 的值。这可能为空,如果 该服务在其进程消失后重新启动;看 onStartCommand(Intent, int, int) 了解详情。

我不太明白restarted after its process has gone away 是什么意思。

我可以通过

轻松避免NPE
@Override
protected void onHandleIntent(@Nullable Intent intent) {
    if (intent == null) {
        return;
    }

    boolean retainStockPriceAlert = intent.getBooleanExtra(RETAIN_STOCK_PRICE_ALERT, true);
    ...
}

但是,我不确定这样做是否正确。

【问题讨论】:

  • 意图是空的还是没有额外内容?
  • intent 本身是null
  • This 可能是 Intent 为空的原因。

标签: android


【解决方案1】:

我可以通过使用来避免 NPE

setIntentRedelivery(true);

IntentService构造函数中

此答案由@Kunu 的参考链接提供 - https://stackoverflow.com/a/37973523/72437

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-14
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多