首页 > 解决方案 > 在启动时启动 Android 服务

问题描述

我正在构建一个在启动时运行的简单服务应用程序。问题是我希望这个应用程序只基于服务,不会有活动。我有 BrodcastReceiever 类和 Service 类,但我不知道该服务将如何在设备上运行。我将运行配置编辑为空。当我添加活动时,它可以工作但正如我所说,这必须只是一个服务应用程序。为什么它不工作?

清单.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.TestService">

    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true">

    </service>

    <receiver android:name=".BootDeviceReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>


</application>

广播接收器.java

public class BootDeviceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.d("testLog","broadCast started");

    if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
      Intent intentService = new Intent(context,MyService.class);
        intentService.setAction(Intent.ACTION_MAIN);
        intentService.addCategory(Intent.CATEGORY_LAUNCHER);

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

日志未显示在 onReceive 函数中。

感谢您的帮助。

标签: androidandroid-service

解决方案


这是不可能的。当您在设备上安装应用程序时,您的组件都处于“停止状态”。在“停止状态”时,它们不会被 Android 触发。为了让您的组件摆脱这种状态,用户必须手动启动您的应用程序至少一次。用户启动您的应用程序的唯一方法是启动一个Activity. 用户启动 an 的唯一方法Activity是让您Activity在您的应用程序中拥有一个,并在您的清单中拥有一个匹配的<activity>声明,其中<intent-filter>包含 ACTION=MAIN 和 CATEGORY=LAUNCHER。


推荐阅读