安卓服务无法启动

4

我正在尝试向我的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>

我的服务...刚刚加入了日志记录功能

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

我的 BroadCastReceiver

public class AttachmentStartupReceiver extends BroadcastReceiver {

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

我无法看到服务在设备启动后启动,日志中没有“oncreate service”,我也查看了设置->应用程序->正在运行的服务。 有人知道我做错了什么吗?
谢谢。

你是否有接收BOOT_COMPLETED的权限? - njzk2
你的广播接收器已被调用? - Bruno Mateus
我的接收器还没有被调用。 - Al Phaba
1个回答

5
您需要将以下权限添加到您的清单文件中。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

默认情况下,BOOT_COMPLETED 不会发送广播。


我已经添加了这个,重新启动了模拟器并在设备上重新部署了我的应用程序,但它仍然无法启动我的服务。还有其他建议吗? - Al Phaba
2
好的,现在它正在运行。权限缺失并且我的接收器没有被安卓找到。在清单文件中更改了接收器名称后,它就可以工作了。正确的接收器元素是: <receiver android:name=".AttachmentStartupReceiver" android:process=":attachServiceBackground" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> - Al Phaba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接