【问题标题】:java.lang.NullPointerException IntentServicejava.lang.NullPointerException IntentService
【发布时间】:2016-11-04 11:54:50
【问题描述】:

我正在尝试在设备上安装的其他应用中启动服务。使用 startService 时出现 NullPointerException

    public void notConnected(){
        Log.i(TAG,"no connection... reconnecting.");
        Intent reset = new Intent("com.famoco.intent.action.TOGGLE_DATA");
        Log.i(TAG,"calling " + reset.getAction());
        if(reset.getAction().equals("com.famoco.intent.action.TOGGLE_DATA"))
        {
            startService(reset);
        }
        else
        {
            Log.i(TAG,"couldn't start service");
        }
}

这是错误日志

E/AndroidRuntime: FATAL EXCEPTION: IntentService[MyAppCommService]
              Process: com.myapppackage.MyApp, PID: 8583
              java.lang.NullPointerException
                  at android.content.ContextWrapper.startService(ContextWrapper.java:494)
                  at com.myapppackage.MyApplocation.activity.MyAppActivity.notConnected(MyAppActivity.java:591)
                  at com.myapppackage.MyApplocation.api.MyAppApi.submitClock(MyAppApi.java:228)
                  at com.myapppackage.MyApplocation.service.MyAppCommService.submitTags(MyAppCommService.java:52)
                  at com.myapppackage.MyApplocation.service.MyAppCommService.onHandleIntent(MyAppCommService.java:98)
                  at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
                  at android.os.Handler.dispatchMessage(Handler.java:110)
                  at android.os.Looper.loop(Looper.java:193)
                  at android.os.HandlerThread.run(HandlerThread.java:61)

原来我的上下文返回 null,我通过在 onCreate 中获取上下文并调用 myContext.startservice 来修复它。

【问题讨论】:

  • 你能分享更多代码吗?
  • 你需要什么代码?
  • 我不知道。也许您需要像这样指定您的服务:startService(new Intent(this, MyService.class));

标签: android android-intent service


【解决方案1】:

您正在开始一个新的Intent。看看那个谷歌的例子,看起来你使用了错误的方法来启动它。

- you use:
startService(reset);

- try this one:
startActivity(intent);

但这会启动一个活动。你想要一项服务。我认为您不能这样做除非您是其他应用的开发者。一般而言,Android 应用无法访问彼此的代码和资源。

【讨论】:

    【解决方案2】:

    通过在onCreate() 中返回上下文然后调用context.startService() 来修复它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-19
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2019-04-14
      • 2014-02-25
      相关资源
      最近更新 更多