思路
使用原生获取,在通过交互,传递至flutter页面。
开始
1、在MainActivity.java中添加交互事件和获取手机剩余空间方法
package com.peiban.app;
import androidx.annotation.NonNull;
import android.os.Environment;
import io.flutter.embedding.android.FlutterActivity;
import android.os.Bundle;
import android.os.StrictMode;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import android.content.Context;
public class MainActivity extends FlutterActivity {
private static final String channel = "nativeApi";
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//新版的Flutter SDK默认使用的是 import io.flutter.embedding.android.FlutterActivity; 包,
// 则在MethodChannel方法中的第一个参数填写 getFlutterEngine().getDartExecutor().getBinaryMessenger()
//如果你使用的Flutter的SDK是旧版本,那么默认的是 import io.flutter.app.FlutterActivity; 包
// 则MethodChannel方法中的第一个参数填写 getFlutterView()
new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(),channel).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
// if (methodCall.method!=null) {
// result.success(getDiskSpace(methodCall.method));
// } else {
// result.notImplemented();
// }
switch (methodCall.method) {
case "get_disk_space":
result.success(getDiskSpace(methodCall.method));
break;
default:
result.notImplemented();
break;
}
}
}
);
}
public String getDiskSpace(String name){
System.out.println("传递的参数是"+name);
// return "您好"+name;
long freeSpaceLong = Environment.getExternalStorageDirectory().getFreeSpace();
String freeSpace = String.valueOf(freeSpaceLong);
return freeSpace;
}
}
2、在ios的appDelegate.m中添加交互
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import <sys/sysctl.h>
#import <mach/mach.h>
#import <AVFoundation/AVFoundation.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
FlutterViewController *controller = (FlutterViewController *)self.window.rootViewController;
//通道标识,要和flutter端的保持一致
FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"nativeApi" binaryMessenger:controller];
//flutter端通过通道调用原生方法时会进入以下回调
[channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
//call的属性method是flutter调用原生方法的方法名,我们进行字符串判断然后写入不同的逻辑
if ([call.method isEqualToString:@"get_disk_space"]) {
//flutter传给原生的参数
id para = call.arguments;
NSLog(@"flutter传给原生的参数:%@", para);
//原生传给flutter的值;
result([NSString stringWithFormat:@"%ld",[self freeDiskSpaceInBytes]]);
}else{
//调用的方法原生没有对应的处理 抛出未实现的异常
result(FlutterMethodNotImplemented);
}
}];
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (NSString *)MBFormatter:(long long)byte
{
NSByteCountFormatter * formater = [[NSByteCountFormatter alloc]init];
formater.allowedUnits = NSByteCountFormatterUseGB;
formater.countStyle = NSByteCountFormatterCountStyleDecimal;
formater.includesUnit = false;
return [formater stringFromByteCount:byte];
}
- (long)totalDiskSpaceInBytes
{
NSError * error = nil;
NSDictionary<NSFileAttributeKey, id> * systemAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
return 0;
}
long long space = [systemAttributes[NSFileSystemSize] longLongValue];
return space;
}
- (long)freeDiskSpaceInBytes
{
if (@available(iOS 11.0, *)) {
[NSURL alloc];
NSURL * url = [[NSURL alloc]initFileURLWithPath:[NSString stringWithFormat:@"%@",NSHomeDirectory()]];
NSError * error = nil;
NSDictionary<NSURLResourceKey, id> * dict = [url resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
if (error) {
return 0;
}
long long space = [dict[NSURLVolumeAvailableCapacityForImportantUsageKey] longLongValue];
return space;
} else {
NSError * error = nil;
NSDictionary<NSFileAttributeKey, id> * systemAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
return 0;
}
long long space = [systemAttributes[NSFileSystemFreeSize] longLongValue];
return space;
}
}
//- (void)applicationDidEnterBackground:(UIApplication *)application {
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
// [[AVAudioSession sharedInstance] setActive:YES error:nil];
//}
//- (void)applicationWillResignActive:(UIApplication *)application {
// // *让app接受远程事件控制,及锁屏是控制版会出现播放按钮
// [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// // *后台播放代码
// AVAudioSession*session=[AVAudioSession sharedInstance];
// [session setActive:YES error:nil];
// [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//}
@end
3、在flutter中调用方法获取值
import 'package:flutter/services.dart';
///获取可用空间
_getFreeDiskSpace() async {
const platform = MethodChannel("nativeApi");
var returnValue = await platform.invokeMethod("get_disk_space");
int? result = await sharedPreferencesGetInt("usedDiskSpace");
setState(() {
freeDiskSpace = returnValue;
usedDiskSpace = result ?? 0;
});
}