我的应用程序将文件发送到 ftp 服务器。我通过 MethodChannel 在 Android 上使用 java 发送文件。
这些部分适合在单线程中完成所有工作。但我想发送带有 AsyncTask (java) 和后台的文件。
另外我需要使用 MethodChannel 将文件上传结果发送到 Flutter。
我怎样才能做到这一点?我尝试在 AsyncTask 的 doInBackground 上使用 MethodChannel.Result 但它给了我这个错误:
Caused by: java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: AsyncTask #2
Run Code Online (Sandbox Code Playgroud)
因此,为了解决“@UiThread必须在主线程上执行”的错误。
我用过这个,
runOnUiThread(new Runnable() {
@Override
public void run() {
//call the methodChannel.invokeMethod here to avoid @UiThread exception
}
});
Run Code Online (Sandbox Code Playgroud)
此外,我还实现了一个新的 MethodChannel 和一个后台类,用于始终在后台与本机通信。
class NativeBackground {
final methodChannel = MethodChannel('your.apps.channel/background');
static NativeBackground _instance;
factory NativeBackground() => _instance ? ? = NativeBackground._();
NativeBackground._() {
handlePlatformChannelMethods();
}
Future <void> handlePlatformChannelMethods() async {
methodChannel.setMethodCallHandler((methodCall) {
print('NativeChanell background...');
print(methodCall.method + '(' + methodCall.arguments + ')');
});
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在应用程序的第一个 build() 方法中使用该 NativeBackground 类来初始化。
归档时间: |
|
查看次数: |
3286 次 |
最近记录: |