android - getApplicationContext() 在服务中返回 null

标签 android service android-context

我在自己的进程中有一个服务,我在 list 中声明了它:

   <service
        android:name="com.discountscatcher.util.PointService"
        android:configChanges="orientation"
        android:process=":pointservice" >
    </service>

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

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

然后我就这样开始了:

    startService(new Intent(getApplicationContext(), PointService.class));

Myactivity OnCreate

有什么想法吗?

最佳答案

您正在不同的进程中运行您的服务,因此它与实际应用程序进程没有通信。

尝试从您的服务中删除这一行

android:process=":pointservice"

应用程序完成后,应用程序上下文变为空。在大多数情况下,不需要在不同的进程中运行该服务。也不推荐。

更多信息请点击此处

  1. Service in another process
  2. service reference Example2

关于android - getApplicationContext() 在服务中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20676233/

相关文章:

android - 前台服务通知需要几秒钟才能显示

android - 使用 MediaRecorder 录制屏幕特定 View

java - 恢复应用程序后上下文为空

android - 区别- ApplicationContext() VS。 ANDROID 中的 Activity 上下文..?

android - SQLiteOpenHelper 提供的所有数据库是否保证在应用程序中使用相同的名称构造是相同的?

Android 从路径加载库

每当我将 onclicklistener 附加到按钮时,Android 应用程序在启动时崩溃

java - 在 Android Studio 中连接到数据库的基本 URL

c# - Web 引用服务错误

android - 在android中声明一个服务(私有(private))