要在Android启动时运行服务而无需活动,可以使用以下解决方法:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 在此处编写服务的逻辑代码
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
...
...
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// 在此处启动服务
Intent serviceIntent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
}
}
}
...
...
...
这样,在Android启动完成后,BootReceiver将接收到BOOT_COMPLETED广播,并启动MyService服务。