Android服务无法启动

Al *_*aba 4 android android-service

我试图添加一个服务到我的Android应用程序,但该服务根本不会启动.我将它添加到我的android清单中,以便它在自己的进程中启动并创建一个广播接收器,它应该在BOOT_COMPLETED之后启动服务.

这是我的清单的一部分

    <service android:process=":attachServiceBackground"
             android:name=".AttachService"
             android:icon="@drawable/camera"
             android:label="@string/attachServiceName" />

    <receiver android:name="AttachmentStartupReceiver"
                android:process=":attachServiceBackground">
        <intent-filter >
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>      
        </intent-filter>

        </receiver>
Run Code Online (Sandbox Code Playgroud)

我的服务......刚刚添加了日志记录

public class AttachService extends Service {
    private static final String TAG = AttachService.class.getSimpleName();


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate service");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }   
}
Run Code Online (Sandbox Code Playgroud)

还有我的BroadCastReceiver

public class AttachmentStartupReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent attachSvc = new Intent(context, AttachService.class);
    context.startService(attachSvc);
}
}
Run Code Online (Sandbox Code Playgroud)

我无法看到服务在启动设备后启动,日志中没有"oncreate service",我也查看了Settings-> Applications-> Running Services.有人知道我做错了吗?

谢谢

小智 5

您需要将以下权限添加到清单文件中

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Run Code Online (Sandbox Code Playgroud)

BOOT_COMPLETED默认不发送广播.

  • 好的,现在它正在运行.许可证丢失了,我的接收器没有被android发现.我在清单中更改了接收者名称后就可以了.正确的接收器元素是<receiver android:name =".AttachmentStartupReceiver"android:process =":attachServiceBackground"> <intent-filter> <action android:name ="android.intent.action.BOOT_COMPLETED"/> </ intent-过滤器> </ receiver> (2认同)