【问题标题】:how to start a foreground service in qt android?如何在 qt android 中启动前台服务?
【发布时间】:2021-04-07 12:29:43
【问题描述】:

我想创建一个前台服务,即使在 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”无效?几乎什么都没有改变,我只是创建“通知”并使用另一个功能启动服务。

【问题讨论】:

    标签: android qt service foreground


    【解决方案1】:

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

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

    以上行应加在&lt;application&gt;之前

    您可以使用简单的 andorid 前台服务来完成。 请从here找到样本。

    【讨论】:

    • 我添加了权限,但错误仍然存​​在。 startForeground 不能从静态上下文中引用。这是什么意思?
    • 你能按照这个例子吗
    • 我照着这个例子做了。事实证明,您可以从 onStart 调用非静态方法,而不是从 onCreate。我从 onStart 调用 startForeground,服务在前台成功运行。谢谢!
    • 好的,欢迎 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2021-09-15
    • 2020-08-31
    • 2017-09-01
    相关资源
    最近更新 更多