Android 服务异常 - 权限被拒绝缺少 INTERNET 权限

Android Service Exception - Permission denied missing INTERNET permission

我偶然发现了一个似乎无法解决的问题。

2 个场景,第一个用户单击一个按钮,该按钮触发 MainActivity 中的一个方法来发出 Web 请求。这行得通,一点问题都没有。

在第二种情况下,我想在后台的服务运行中自动发出此请求,一旦代码移入服务,它就会产生权限异常。

Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

我可以很好地启动该服务,但如果我将任何网络请求移动到该服务中,就会遇到权限问题。

我的 AndroidManifest.xml 文件中已经有 <uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

在启动服务之前,我还在我的 MainActivity 中进行了实时权限检查(SDK 23+),但这似乎对服务获得的权限没有影响。

有什么想法吗?

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="domain">

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name="domain.RemoteCommunicationService"
        android:isolatedProcess="true"
        android:exported="true">
    </service>
    <receiver android:name="domain.RemoteServiceRestartReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="domain.RemoteServiceRestart"></action>
        </intent-filter>
    </receiver>
    <receiver android:name="domain.RemoteCommunicationService$RemoteCommunicationReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="domain.RemoteCommunication.ToggleLight"></action>
        </intent-filter>
    </receiver>
</application>

您已使用 isolateProcesstrue。阅读文档所说的内容:

If set to true, this service will run under a special process that is isolated from the rest of the system and has no permissions of its own. The only communication with it is through the Service API (binding and starting).