在Flutter启动Android的后台服务

本文介绍了如何在Flutter应用中启动Android的后台服务。通过创建MethodChannel,Flutter可以调用Android原生的startService()方法。详细步骤包括:在Flutter应用中设置按钮触发服务,创建并注册MyApplication和MyService,以及在MainActivity中处理MethodChannel。
摘要由CSDN通过智能技术生成

背景

(本文翻译自YouTube视频:https://www.youtube.com/watch?v=NXuAzXY_KOo&t=572s
Android和iOS在后台服务的处理方式不同,因此Flutter并没有在这方面做统一处理,而是需要调用原生平台的代码来实现该功能,下面就简单介绍如何在Flutter中与Android的后台服务进行交互。

实现

  1. 在Flutter中有一个按钮,点击后会开启后台服务。此外建立了一个MethodChannel,通过该通道去调用Android原生代码里的 startService()。
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          child: Text("开启后台任务"),
          onPressed: () {
            startService();
          },
        ),
      )
    );
  }

  void startService() async{
    if(Platform.isAndroid) {
      var methodChannel = MethodChannel("com.example.flutterapp");
      String data = await methodChannel.invokeMethod("startService");
      print("data: $data");
    }
  }
}
  1. 新建 MyApplication 继承自 FlutterApplication,并在 onCreate() 中创建 NotificationChannel 和 NotificationManager (Android 26 以上需要)。
public class MyApplication extends FlutterApplication {

    @Override
    public void onCreate() {
        super.onCreate();

        //Android 8.0  26
        //一种 Notification 对应一个 NotificationChannel
        //在 Application 注册 channel 可以在 app 启动时就完成注册
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("messages", "Messages", NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }
}
  1. 新建 MyService 继承自 Service,并在 onCreate() 中进行 Android 版本判断,对 26以上进行特殊处理(记得在 AndroidManifest 里注册 service)。
public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "messages")
                    .setContentText("正在后台运行")
                    .setContentTitle("Flutter后台")
                    .setSmallIcon(R.drawable.launch_background);

            startForeground(101, builder.build());
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
  1. 最后,在 MainActivity 中打开 注册 MethodChannel 并提供 startService() 给 Flutter 调用。
public class MainActivity extends FlutterActivity {

  private Intent serviceIntent;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

    serviceIntent = new Intent(MainActivity.this, MyService.class);

    new MethodChannel(getFlutterView(), "com.example.flutterapp")
            .setMethodCallHandler(new MethodChannel.MethodCallHandler() {
              @Override
              public void onMethodCall(@NonNull MethodCall methodCall, @NonNull MethodChannel.Result result) {
                if(methodCall.method.equals("startService")) {
                  startService();
                  result.success("服务已启动");
                }
              }
            });
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    stopService(serviceIntent);
  }

  private  void startService() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      startForegroundService(serviceIntent);
    } else {
      startService(serviceIntent);
    }
  }
}

最终效果如下图所示,一开始没有后台任务,点击按钮后,再查看通知栏,发现后台服务已启动。在这里插入图片描述
在这里插入图片描述

好的,让我来回答你的问题。 对于获取Android照片地址,可以使用flutter中的image_picker插件来实现。首先在pubspec.yaml文件中添加依赖: ``` dependencies: image_picker: ^0.6.7+22 ``` 然后在需要获取照片的位置调用以下代码即可: ```dart import 'package:image_picker/image_picker.dart'; final picker = ImagePicker(); final pickedFile = await picker.getImage(source: ImageSource.gallery); if (pickedFile != null) { final String path = pickedFile.path; // do something with the image path } ``` 对于Flutter项目安卓配置启动图片,可以在Android的项目目录下的`android/app/src/main/res`文件夹中放置启动图片。具体命名规则和尺寸可以参考Flutter官方文档:https://flutter.dev/docs/development/ui/advanced/splash-screen。在Android的`AndroidManifest.xml`文件中添加以下代码即可: ```xml <application android:name="io.flutter.app.FlutterApplication" android:icon="@mipmap/ic_launcher" android:label="your_app_name" android:theme="@style/LaunchTheme"> <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/Theme.AppCompat.Light.NoActionBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="@drawable/launch_background" /> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> ``` 其中`@drawable/launch_background`指的是启动图片的名称。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值