如何在Android设备开启时启动服务?

Adh*_*ham 8 android

如何在启动serviceAndroid设备并运行操作系统时启动?

cis*_*mbo 24

添加到AndroidManifest.xml:

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

<service android:name=".YourService" />

<receiver android:name="com.your.package.AutoStart">  
    <intent-filter>  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>  
</receiver>
Run Code Online (Sandbox Code Playgroud)

创建类AutoStart.java:

public class AutoStart extends BroadcastReceiver
{

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

}
Run Code Online (Sandbox Code Playgroud)

  • 但是 BroadcastReceiver 是否会在设备完成启动后立即开始接收广播,而无需运行应用程序?如果是,广播接收器什么时候注册? (2认同)
  • 是的,操作系统将在设备启动时调用AutoStart.onReceive()方法.请注意,这可能是在安装SD卡之前.当您安装apk时,系统将查看您的清单,您的应用程序将在系统中注册,以便您在启动时启动. (2认同)