android - 在启动时启动 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 函数中。
感谢您的帮助。
解决方案
这是不可能的。当您在设备上安装应用程序时,您的组件都处于“停止状态”。在“停止状态”时,它们不会被 Android 触发。为了让您的组件摆脱这种状态,用户必须手动启动您的应用程序至少一次。用户启动您的应用程序的唯一方法是启动一个Activity
. 用户启动 an 的唯一方法Activity
是让您Activity
在您的应用程序中拥有一个,并在您的清单中拥有一个匹配的<activity>
声明,其中<intent-filter>
包含 ACTION=MAIN 和 CATEGORY=LAUNCHER。
推荐阅读
- python - SimCLR 不学习表示
- google-sheets - 带有 iferror 和 regexmatch 的数组?
- node.js - 错误发生意外错误:在创建新的反应应用程序时
- python - 将页面标题传递到 url
- tensorflow - AttributeError:模块 'keras.layers' 没有属性 'Wrapper'
- python - 如何在 Python 中运行我的 Selenium Headerless
- python - 如何为网络中的不同节点分配不同的颜色?
- javascript - 如何根据位置更改粘性向上箭头按钮的属性?
- ios - Cupertino Datepicker 在 Flutter 中无法正确渲染
- google-cloud-platform - 即使启用了自动存储增加,SQL 导入作业也会导致磁盘已满