尝试在启动Android上启动服务 [英] Trying to start a service on boot on Android

查看:152
本文介绍了尝试在启动Android上启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图启动服务时,设备启动时在Android上,但我不能得到它的工作。我已经在多个环节在网上看了,但没有一个code工作。我是不是忘了什么东西?

I've been trying to start a service when a device boots up on android, but I cannot get it to work. I've looked at a number of links online but none of the code works. Am I forgetting something?

<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" />

的BroadcastReceiver

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");
    }
}

感谢

推荐答案

其他答案看起来不错,但我想我的一切包装成一个完整的答案。

The other answers look good, but I thought I'd wrap everything up into one complete answer.

您需要在AndroidManifest.xml文件如下:

You need the following in your AndroidManifest.xml file:

1)在你的&LT;舱单&GT;元素:

1) In your <manifest> element:

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


2)在你的&lt;应用&GT;元(一定要使用完全合格的[或相对]类的名称为您的BroadcastReceiver):


2) In your <application> element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver):

<receiver android:name="com.example.MyBroadcastReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>  
</receiver>

(你不需要了android:启用,出口等,属性... Android的默认设置是正确的)

(you don't need the android:enabled, exported, etc., attributes... the Android defaults are correct)

在MyBroadcastReceiver.java:

In 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);
    }
}



从原来的问题:



From the original question:

  • 在目前还不清楚如果&lt;接收器GT;内容是在&lt;用途&gt;元素
  • 在目前还不清楚如果指定了的BroadcastReceiver正确的完全限定(或相对)的类名
  • 有在&lt一个错字;意向性滤光器&gt;

这篇关于尝试在启动Android上启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆