应用启动时Android启动系统服务

时间:2013-04-10 16:13:16

标签: android broadcastreceiver

在AndroidManifest.xml中,我将一个BroadcastReceiver注册到" android.intent.action.BOOT_COMPLETED"事件。 这会在每次Android设备启动时启动服务。

...
        <receiver android:name="MySystemScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
...

但是,我希望在安装应用程序后立即启动系统服务,而无需重启设备。

应用程序启动时是否可以使用系统事件? 或者我是否需要设置自定义事件?

我应该将清单文件修改为

...
        <receiver android:name="MySystemScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="com.myapp.StartSysService" />
            </intent-filter>
        </receiver>
...

然后使用类似

的主要活动启动服务
...
        Intent intent = new Intent();
        intent.setAction("com.myapp.StartSysService");
        sendBroadcast(intent);
...

如果是,我应该使用哪种方法? (onCreate,onResume ...)

由于

1 个答案:

答案 0 :(得分:4)

您可以继承Application,它具有onCreate()回调。你可以在那里开始你的服务。

public class MyApplication extends Application {
    public void onCreate() {
        // start your service
    }
}

在清单的<application>标记中,添加android:name="MyApplication"