开机后BroadcastReceiver无法启动前台服务

3

我想启动一个前台服务。当我从活动中启动服务时,一切正常。但是当我通过广播接收器在启动/启动时启动服务时,服务从未启动。(也许它正在运行并立即被销毁。无论如何,我看不到通知图标)

我的手机使用的是Android 10,minSdkVersion为26,compileSdkVersion为29。

这是我的清单文件:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application...>

    <service android:name="de.ggg.location.PositionIntervallService"
        android:enabled="true"></service>

    <receiver android:name="de.ggg.location.StartupRecevier">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
</application>

创业公司接收器:

public class StartupRecevier extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg) {
        Intent intent = new Intent(context, PositionIntervallService.class);
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        }
    }
}

The PositionIntervallService:

public class PositionIntervallService extends Service {
     @Override
     public void onCreate() {
       startForeground(FOREGROUND_ID, buildForegroundNotification(chan));

       // important work here
     }
}

我做错了什么?

2个回答

2

您可以替换:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

使用:

ContextCompat.startForegroundService(context, intent);

这应该可以工作。

0
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

谢谢。我已经在清单文件中添加了这行代码,但是服务仍然没有被调用。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接