You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter项目中用Java实现Android开机自启保活后台服务咨询

Flutter Android端后台服务实现方案

1. FlutterActivity中启动前台服务

安卓8.0及以上系统必须使用前台服务方式启动,否则会被系统直接杀死:

  • 在MainActivity.java的onCreate方法中添加启动逻辑:
import android.content.Intent;
import android.os.Build;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;

public class MainActivity extends FlutterActivity {
    @Override
    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 启动后台服务
        Intent serviceIntent = new Intent(this, ServiceBack.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
    }
}
  • 在ServiceBack.java中添加前台通知绑定逻辑,必须在服务启动后5秒内调用startForeground,否则会触发ANR:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;

public class ServiceBack extends android.app.Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 创建通知渠道(安卓8.0+要求)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "BACK_SERVICE_CHANNEL",
                    "后台运行服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        // 构建前台服务通知
        Notification notification = new NotificationCompat.Builder(this, "BACK_SERVICE_CHANNEL")
                .setContentTitle("应用后台运行中")
                .setContentText("正在执行后台任务")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        // 绑定前台服务,ID不能为0
        startForeground(1001, notification);
        // 服务被系统杀死后自动重启
        return START_STICKY;
    }
}

2. 开机自启配置

  • 先在AndroidManifest.xml中添加所需权限:
<!-- 开机广播接收权限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- 前台服务权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- 忽略电池优化权限申请权限 -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
  • 新建开机广播接收器BootReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

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, ServiceBack.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent);
            } else {
                context.startService(serviceIntent);
            }
        }
    }
}
  • 在AndroidManifest.xml中注册广播接收器:
<receiver
    android:name=".BootReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

注意:开机自启需要用户手动在系统应用权限管理中打开「允许自启动」开关,不同厂商路径不同,如小米在安全中心-应用管理-权限管理,华为在手机管家-应用启动管理中设置。

3. Android 11后台保活配置

  • 给服务添加前台服务类型声明,在AndroidManifest.xml的service标签中添加属性,根据服务实际用途选择对应type:
<service
    android:name=".ServiceBack"
    android:enabled="true"
    android:exported="false"
    android:foregroundServiceType="dataSync|mediaPlayback" />
  • 申请忽略电池优化权限,在MainActivity.java的onCreate方法中添加请求逻辑,可大幅降低系统查杀概率:
import android.os.PowerManager;
import android.provider.Settings;
import android.net.Uri;

// 放在onCreate方法中
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    String packageName = getPackageName();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (!pm.isIgnoringBatteryOptimizations(packageName)) {
        Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
        startActivityForResult(intent, 1002);
    }
}
  • 不要使用bindService方式绑定服务,绑定服务会和Activity生命周期关联,Activity销毁时服务会同步被回收,仅使用startForegroundService方式启动即可。
  • 避免在服务中执行长时间阻塞操作,可每隔2-3分钟执行一次轻量心跳逻辑,避免系统判定服务为空闲状态被回收。

内容的提问来源于stack exchange,提问作者Nautilus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:57:05