繁体   English   中英

在引导时启动 Android 服务

[英]Starting Android Service on Boot Time

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

清单.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>

BroadcastReceiver.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 function 中。

感谢您的帮助。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM