• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

android - 尝试在 Android 上启动服务

[复制链接]
菜鸟教程小白 发表于 2022-8-1 01:20:10 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

当设备在 android 上启动时,我一直在尝试启动服务,但我无法让它工作。我在网上查看了许多链接,但没有一个代码有效。我是不是忘记了什么?

AndroidManifest.xml

<receiver
    android:name=".StartServiceAtBootReceiver"
    android:enabled="true"
    android:exported="false"
    android:label="StartServiceAtBootReceiver" >
    <intent-filter>
        <action android:name="android.intent.action._BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<service
    android:name="com.test.RunService"
    android:enabled="true" />

广播接收器
public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent serviceLauncher = new Intent(context, RunService.class);
        context.startService(serviceLauncher);
        Log.v("TEST", "Service loaded at start");
    }
}



Best Answer-推荐答案


其他答案看起来不错,但我想我会将所有内容都打包成一个完整的答案。

您的 AndroidManifest.xml 中需要以下内容文件:

  • 在您的 <manifest>元素:
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
  • 在您的 <application>元素(确保为您的 BroadcastReceiver 使用完全限定的 [或相对] 类名):
    <receiver android:name="com.example.MyBroadcastReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
        </intent-filter>  
    </receiver>
    

    (你不需要 android:enabledexported 等,属性:Android默认是正确的)

    MyBroadcastReceiver.java :
    package com.example;
    
    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent startServiceIntent = new Intent(context, MyService.class);
            context.startService(startServiceIntent);
        }
    }
    

  • 从原来的问题:
  • 尚不清楚 <receiver>元素位于 <application>元素
  • 不清楚 BroadcastReceiver 的完全限定(或相对)类名是否正确。已指定
  • <intent-filter> 中有错字
  • 关于android - 尝试在 Android 上启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2784441/

    回复

    使用道具 举报

    懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    关注0

    粉丝2

    帖子830918

    发布主题
    阅读排行 更多
    广告位

    扫描微信二维码

    查看手机版网站

    随时了解更新最新资讯

    139-2527-9053

    在线客服(服务时间 9:00~18:00)

    在线QQ客服
    地址:深圳市南山区西丽大学城创智工业园
    电邮:jeky_zhao#qq.com
    移动电话:139-2527-9053

    Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap