如何在qtandroid中启动前台服务



我想创建一个前台服务,即使在qt中关闭应用程序后也能工作。我读了https://doc.qt.io/qt-5/android-services.html简单的服务工作成功,但当我尝试在我的功能中启动前台服务时

public static void startQtAndroidService(Context context) {
/*context.startService(new Intent(context, smsForwardService.class));
Log.i("smsForwardService", "Service started");
*/
Intent notificationIntent = new Intent(context, smsForwardService.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(context, "i don't know what is it, so i just put this text here")
.setContentTitle("SMSForwardService")
.setContentText("Service working")
.setContentIntent(pendingIntent)
.build();
// Notification ID cannot be 0.
startForeground(666, notification);
}

编译器给我写这个

:-1: ERROR: D:projectsFKeybuild-FKey-Android_Qt_5_15_1_Clang_Multi_Abi_05487b-Debugandroid-buildsrcsmsForwardService.java:54: error: non-static method startForeground(int,Notification) cannot be referenced from a static context
startForeground(666, notification);
^
Note: Some input files use or override a deprecated API.

我做错了什么?为什么";startService";工作,但是";startForeground";不起作用?实际上什么都没有改变,我只是创造了";"通知";并用另一个功能启动服务。

您必须在AndroidManifest.xml中定义FOREGROUND_SERVICE权限

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

上述行应添加在<application>之前

你可以用andrid的简单前台服务来做到这一点。请从这里找到样品。

最新更新