【Flutter】獲取手機剩余可使用空間大小

思路

使用原生獲取托猩,在通過交互模庐,傳遞至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;
    });
  }
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末旬渠,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子端壳,更是在濱河造成了極大的恐慌告丢,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件损谦,死亡現場離奇詭異岖免,居然都是意外死亡岳颇,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門颅湘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來话侧,“玉大人,你說我怎么就攤上這事闯参≌芭簦” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵鹿寨,是天一觀的道長新博。 經常有香客問我,道長释移,這世上最難降的妖魔是什么叭披? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮玩讳,結果婚禮上,老公的妹妹穿的比我還像新娘嚼贡。我一直安慰自己熏纯,他們只是感情好,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布粤策。 她就那樣靜靜地躺著樟澜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪叮盘。 梳的紋絲不亂的頭發(fā)上秩贰,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天,我揣著相機與錄音柔吼,去河邊找鬼毒费。 笑死,一個胖子當著我的面吹牛愈魏,可吹牛的內容都是我干的觅玻。 我是一名探鬼主播,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼培漏,長吁一口氣:“原來是場噩夢啊……” “哼溪厘!你這毒婦竟也來了?” 一聲冷哼從身側響起牌柄,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤畸悬,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后珊佣,有當地人在樹林里發(fā)現了一具尸體蹋宦,經...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡披粟,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了妆档。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片僻爽。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖贾惦,靈堂內的尸體忽然破棺而出胸梆,到底是詐尸還是另有隱情,我是刑警寧澤须板,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布碰镜,位于F島的核電站,受9級特大地震影響习瑰,放射性物質發(fā)生泄漏绪颖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一甜奄、第九天 我趴在偏房一處隱蔽的房頂上張望柠横。 院中可真熱鬧,春花似錦课兄、人聲如沸牍氛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽搬俊。三九已至,卻和暖如春蜒茄,著一層夾襖步出監(jiān)牢的瞬間唉擂,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工檀葛, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留玩祟,地道東北人。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓驻谆,卻偏偏與公主長得像卵凑,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子胜臊,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內容