Code

Code

วันพฤหัสบดีที่ 3 กันยายน พ.ศ. 2558

ANDROID : CONNECTION DETECTOR (Class : สำหรับตรวจจับการเชื่อมต่ออินเตอร์เน็ต)

SmartPhone ในปัจจุบัน ส่วนใหญ่นั้นจะมีการเชื่อมต่อ internet อยู่แล้ว วันนี้จึงมานำเสนอ class ที่เอาไว้ตรวจสอบว่า เครื่องที่ใช้งานแอพอยู่นั้น ได้ทำการเชื่อมต่อ internet หรือไม่

การใช้งานก็ไม่ยากซับซ้อนอะไรมาก ตามนี้เลยย โดยต้องส่ง context ไปกับเมธอดด้วยนะ


1
2
3
4
5
6
if (ConnectionDetector.isConnectingToInternet(context)){
            Toast.makeText(context,"ตอนนี้มีการเชื่อมต่ออินเตอร์เน็ตอยู่นะ / Internet Connection",Toast.LENGTH_SHORT).show();
}else{
            Toast.makeText(context,"ตอนนี้ไม่มีการเชื่อมต่ออินเตอร์เน็ต / No Internet connection",Toast.LENGTH_SHORT).show();

        }

แต่ด้วยก่อน อย่าลืมไปเปิด permission ใน AndroidManifest.xml ด้วยนะ ตามนี้


1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

ส่วน Code Class ConnectionDetector อยู่ตรงนี้



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.royle.connectionDetector;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by royle on 9/04/2015.
 */

public class ConnectionDetector {

 public static boolean isConnectingToInternet(Context context){
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
}

Good Luck <3 data-blogger-escaped-br="">

ไม่มีความคิดเห็น :

แสดงความคิดเห็น