getApplicationContext()在Service中返回null

whi*_*key 8 service android android-context

我有一个服务在它自己的过程中,我已经在清单中声明它:

   <service
        android:name="com.discountscatcher.util.PointService"
        android:configChanges="orientation"
        android:process=":pointservice" >
    </service>
Run Code Online (Sandbox Code Playgroud)

onStartCommand我试图得到一个ApplicationContext,但它总是返回null,我能忘记什么?

    public int onStartCommand(Intent intent, int flags, int startId) {
    android.os.Debug.waitForDebugger();
    Context mContext = getApplicationContext();
    return Service.START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

我这样开始:

    startService(new Intent(getApplicationContext(), PointService.class));
Run Code Online (Sandbox Code Playgroud)

Myactivity OnCreate

有任何想法吗?

kal*_*pvs 6

您正在Service以不同的流程运行,因此它与实际应用程序进程无法通信.

尝试从您的服务中删除此行

android:process=":pointservice"
Run Code Online (Sandbox Code Playgroud)

应用程序完成后,应用程序上下文变为空.在大多数情况下,不需要在不同的进程中运行服务.也不建议这样做.

有关更多信息,请点击此处

  1. 在另一个过程中服务
  2. 服务参考例2