如何在Qt Android中启动前台服务?

3
我想创建一个前台服务,在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:\projects\FKey\build-FKey-Android_Qt_5_15_1_Clang_Multi_Abi_05487b-Debug\android-build\src\smsForwardService.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" 不能运行?几乎没有改变,我只是创建了 "notification" 并使用另一个函数启动服务。
1个回答

2

AndroidManifest.xml中定义FOREGROUND_SERVICE权限。

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

<application>标签之前添加上述行。

您可以使用简单的Android前台服务来完成此操作。请从这里查找示例。


我已经添加了权限,但是错误仍然存在。startForeground无法从静态上下文中引用。这是什么意思? - Max Barinov
1
请你能否按照这个例子来做? - Nensi Kasundra
我按照示例所说的去做了,结果发现你可以从onStart调用非静态方法,但不能从onCreate调用。我从onStart中调用startForeground,服务成功地在前台运行。谢谢! - Max Barinov
好的,欢迎 :) - Nensi Kasundra

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