Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Reachability 做全域網路狀態監聽

編輯:關於 Android 程式設計

在 AppDelegate 中註冊 Reachability 的通知,就能在全域範圍掌握網路狀態的變化;一旦連線中斷,立刻彈出提示。

註冊監聽並啟動 Notifier

Reachability 會在狀態改變時發送通知,因此先加入觀察者,再指定要監看的主機並啟動。

// 網路檢測
[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(reachabilityChanged:)
                                            name:kReachabilityChangedNotification
                                          object:nil];

hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
[hostReach startNotifier];

狀態變化時的回呼

通知觸發後,從通知物件取回 Reachability 實例,再查詢目前的網路狀態即可決定後續處理。

- (void)reachabilityChanged:(NSNotification*)note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);

    NetworkStatus status = [curReach currentReachabilityStatus];

    if (status == NotReachable) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setBool:1 forKey:@"network"];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接被斷開"
                                                       message:nil
                                                      delegate:nil
                                             cancelButtonTitle:@"確定"
                                             otherButtonTitles:nil];
        [alert show];
        [alert release];
    } else {
        // 網路恢復,此處可視需要加入還原邏輯
    }
}

實務上有幾點值得留意:Reachability 只能反映「有沒有可達的路徑」,並不代表網路品質或伺服器是否真的回應,因此不能取代請求本身的逾時處理。另外記得在 dealloc 中執行 [[NSNotificationCenter defaultCenter] removeObserver:self] 並停止 notifier,避免通知發送到已釋放的物件。若使用較新的 iOS SDK,UIAlertView 已被棄用,建議改用 UIAlertController。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved