android - Intent 始终为 null onStartCommand

标签 android android-intent service android-activity

我有以下代码

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(intent != null) {
        Log.i("INTENT", intent.getAction().toString());
    }
    return START_STICKY;
}

但它总是在线返回 NullPointerException:

Log.i("INTENT", intent.getAction().toString());

为什么?我在上面检查“intent”变量是否不为空。如果是这种情况,请执行以下代码。但我仍然遇到 nullpointerexception。

服务是从这样的 Activity 开始的:

startService(new Intent(this, MainService.class));

我做错了什么?

最佳答案

你得到一个 NullPointerException 因为 intent.getAction() 似乎返回 null

您应该将支票扩展到:

if(intent != null && intent.getAction() != null) {

如果你想为你的 Intent 添加一个 Action ,你需要调用 setAction() :

Intent i = new Intent(this, MainService.class);
i.setAction("foo");
startService(i);

关于android - Intent 始终为 null onStartCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16043173/

相关文章:

Android ListView 预加载行数据

java - 如何在 Android 中将 pdf 附加到发送 Intent (发送到电子邮件、保管箱等)

android - 单击可扩展 ListView 项/子项时无法启动/打开 Activity 以及如何在此处实现 Toast

symfony - 从命令类访问参数

java - 退出后杀死应用程序进程吗?

java - 安卓第 3 方集成

android - 如何让用户一次只能从一台设备登录

java - Putextra 不断发送第一个输入的数据

android - 如何在两个 Activity 之间传递照片(位图)?

wcf - iis7 wcf : on local computer I get 401 - Unauthorized: Access is denied due to invalid credentials