안드로이드 WIfiManager 로 주변 wifi 스캔하기! Android WifiManager scan access point wifi list

2019. 6. 14. 10:09·IT기술 관련/모바일
반응형

출처: https://altongmon.tistory.com/694 [IOS를 Java]

 

이번 포스팅에서는 WifiManager 클래스를 사용해서 주변 ap(Access Point) wifi목록을

스캔하는 예제입니다.

실행 결과 먼저 보여드립니다.

아래 정보들 말고도 더 확인할 수 있는데, 저는 이렇게만 만들었습니다.

 

먼저

Manifest.xml에 아래 퍼미션들을 추가해줍니다.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-feature android:name="android.hardware.wifi"/>

 

그리고 저는 데이터 바인딩을 사용하기 때문에

build.gradle(Module:app) 을 열어

android{} 중괄호 블록 내부에

dataBinding {
enabled true
}

데이터 바인딩을 허용하는 코드를 넣어줍니다.

 

그리고 레이아웃에서 저는 CardView 와 RecyclerView를 둘 다 사용했는데요.

그래서 

dependencies {

}

블록에 아래 3가지를 implementation해줍니다.

implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'

 

데이터를 담을 AccessPoint 클래스와 RecyclerView에 데이터를 넣어주고 처리하기 위한

RecyclerViewAdapter 클래스를 상속 받는 AccessPointAdapter 도 만드러 줍니다.

 

AccessPoint.java

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

public class AccessPoint {

 

    private String ssid;

    private String bssid;

    private String rssi;

 

    public AccessPoint(String ssid, String bssid, String rssi) {

        this.ssid = ssid;

        this.bssid = bssid;

        this.rssi = rssi;

    }

 

    public String getSsid() {

        return ssid;

    }

 

    public String getBssid() {

        return bssid;

    }

 

    public String getRssi() {

        return rssi;

    }

}

 

Colored by Color Scripter

cs

 

AccessPointAdapter.java

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

public class AccessPointAdapter extends RecyclerView.Adapter {

 

    private Vector<AccessPoint> accessPoints;

    private Context context;

 

    AccessPointAdapter(Vector<AccessPoint> accessPoints, Context context) {

        this.accessPoints = accessPoints;

        this.context = context;

    }

 

    @NonNull

    @Override

    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder holder;

        ItemAccesspointBinding binding = ItemAccesspointBinding.inflate(LayoutInflater.from(context), parent, false);

        holder = new AccessPointHolder(binding);

        return holder;

    }

 

    @Override

    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        AccessPointHolder accessPointHolder = (AccessPointHolder)holder;

        final ItemAccesspointBinding binding = accessPointHolder.binding;

        binding.cardView.setRadius(20.0f);

        String ssid = "SSID : " + accessPoints.get(position).getSsid();

        String bSsid = "BSSID : " + accessPoints.get(position).getBssid();

        String rssi = "RSSI : " + accessPoints.get(position).getRssi();

        binding.ssidTextView.setText(ssid);

        binding.bssidTextView.setText(bSsid);

        binding.rssiLevelTextView.setText(rssi);

 

    }

 

    @Override

    public int getItemCount() {

        return accessPoints.size();

    }

 

    private class AccessPointHolder extends RecyclerView.ViewHolder {

        ItemAccesspointBinding binding;

 

        AccessPointHolder(ItemAccesspointBinding binding) {

            super(binding.getRoot());

            this.binding = binding;

        }

    }

 

}

 

Colored by Color Scripter

cs

 

---------------------------------------------------------------------------------------------------------

 

---------------------------------------------------------------------------------------------------------

 

 

 

 

 

이제 xml 차례입니다.

 

recyclerView의 아이템으로 들어갈 layout

item_accesspoint.xml

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto">

 

    <android.support.v7.widget.CardView

        android:layout_margin="10dp"

        android:id="@+id/cardView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content">

 

        <android.support.constraint.ConstraintLayout

            android:padding="10dp"

            android:background="@color/colorAccent"

            android:id="@+id/cardLayout"

            android:layout_width="match_parent"

            android:layout_height="wrap_content">

            <TextView

                app:layout_constraintTop_toTopOf="@+id/cardLayout"

                app:layout_constraintStart_toStartOf="@+id/cardLayout"

                app:layout_constraintBottom_toTopOf="@+id/bssidTextView"

                android:id="@+id/ssidTextView"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:textSize="@dimen/textSize"/>

            <TextView

                app:layout_constraintStart_toStartOf="@+id/ssidTextView"

                app:layout_constraintTop_toBottomOf="@+id/ssidTextView"

                app:layout_constraintBottom_toTopOf="@+id/rssiLevelTextView"

                android:id="@+id/bssidTextView"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:textSize="@dimen/textSize" />

            <TextView

                app:layout_constraintStart_toStartOf="@+id/ssidTextView"

                app:layout_constraintTop_toBottomOf="@+id/bssidTextView"

                app:layout_constraintBottom_toBottomOf="@+id/cardLayout"

                android:id="@+id/rssiLevelTextView"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:textSize="@dimen/textSize" />

        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

 

</layout>

Colored by Color Scripter

cs

 

여기서 사용된 @dimen/textSize 는 20sp 입니다.

 

activity_main.xml

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

29

30

31

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools">

 

    <android.support.constraint.ConstraintLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:context="wifi.rowan.com.wifilistscanner.MainActivity">

        <android.support.v7.widget.Toolbar

            android:background="@color/colorPrimary"

            android:id="@+id/toolbar"

            app:layout_constraintTop_toTopOf="parent"

            app:layout_constraintBottom_toTopOf="@+id/accessPointRecyclerView"

            android:layout_width="match_parent"

            android:layout_height="wrap_content">

            <TextView

                android:textColor="#FFFFFFFF"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="center"

                android:text="Wifi List"/>

        </android.support.v7.widget.Toolbar>

        <android.support.v7.widget.RecyclerView

            app:layout_constraintTop_toBottomOf="@+id/toolbar"

            app:layout_constraintBottom_toBottomOf="parent"

            android:id="@+id/accessPointRecyclerView"

            android:layout_width="match_parent"

            android:layout_height="0dp"/>

    </android.support.constraint.ConstraintLayout>

</layout>

Colored by Color Scripter

cs

 

마지막으로

MainActivity.java

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

public class MainActivity extends AppCompatActivity {

 

    Vector<AccessPoint> accessPoints;

    LinearLayoutManager linearLayoutManager;

    AccessPointAdapter accessPointAdapter;

    WifiManager wifiManager;

    List<ScanResult> scanResult;

    ActivityMainBinding binding;

    /* Location permission 을 위한 필드 */

    public static final int MULTIPLE_PERMISSIONS = 10; // code you want.

    // 원하는 권한을 배열로 넣어줍니다.

    String[] permissions = new String[]{

            Manifest.permission.ACCESS_COARSE_LOCATION

    };

    /* Location permission 을 위한 필드 */

 

    @Override

    protected void onStart() {

        super.onStart();

        if (Build.VERSION.SDK_INT >= 23) {

            if (!checkPermissions()) {

                finish();

            }

        }

    }

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);

        binding.accessPointRecyclerView.setLayoutManager(linearLayoutManager);

        accessPoints = new Vector<>();

        if (wifiManager != null) {

            if (!wifiManager.isWifiEnabled()) {

                wifiManager.setWifiEnabled(true);

            }

            final IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

            filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

            registerReceiver(mWifiScanReceiver, filter);

            wifiManager.startScan();

        }

    }

 

 

    private BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {

 

        @Override

        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();

            if (action != null) {

                if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {

                    getWIFIScanResult();

                    wifiManager.startScan();

                } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {

                    context.sendBroadcast(new Intent("wifi.ON_NETWORK_STATE_CHANGED"));

                }

 

            }

 

        }

    };

 

    public void getWIFIScanResult() {

        scanResult = wifiManager.getScanResults();

        if (accessPoints.size() != 0) {

            accessPoints.clear();

        }

        for (int i = 0; i < scanResult.size(); i++) {

            ScanResult result = scanResult.get(i);

            if (result.frequency < 3000) {

                Log.d(". SSID : " + result.SSID,

                        result.level + ", " + result.BSSID);

                accessPoints.add(new AccessPoint(result.SSID, result.BSSID, String.valueOf(result.level)));

            }

        }

        accessPointAdapter = new AccessPointAdapter(accessPoints, MainActivity.this);

        binding.accessPointRecyclerView.setAdapter(accessPointAdapter);

        accessPointAdapter.notifyDataSetChanged();

    }

 

    @Override

    protected void onDestroy() {

        super.onDestroy();

        unregisterReceiver(mWifiScanReceiver);

    }

 

    /* Location permission 을 위한 메서드들 */

    private boolean checkPermissions() {

        int result;

        List<String> listPermissionsNeeded = new ArrayList<>();

        for (String p : permissions) {

            result = ContextCompat.checkSelfPermission(MainActivity.this, p);

            if (result != PackageManager.PERMISSION_GRANTED) {

                listPermissionsNeeded.add(p);

            }

        }

        if (!listPermissionsNeeded.isEmpty()) {

            ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);

            return false;

        }

        return true;

    }

 

    @Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {

            case MULTIPLE_PERMISSIONS: {

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.d("permission", "granted");

                }

            }

        }

    }

/* Location permission 을 위한 메서드들 */

}

 

Colored by Color Scripter

cs

 

코드를 보고 순서대로 따라하시면 큰 어려움 없이 하실 수 있을 거에요^^

이상입니다.

감사합니다.



출처: https://altongmon.tistory.com/694 [IOS를 Java]

반응형

'IT기술 관련 > 모바일' 카테고리의 다른 글

[Volley][Java]volley로 json데이터받기(3)  (0) 2019.06.26
[안드로이드] extends Fragment 구현시 context 구하는 방법  (0) 2019.06.26
android kotlin - WebView example -안드로이드 코틀린 웹뷰  (0) 2019.06.14
안드로이드 스튜디오 - GitHub 연동과 add, commit, push 개념  (0) 2019.06.11
[Marshmallow] 권한 요청 방법  (0) 2019.06.08
'IT기술 관련/모바일' 카테고리의 다른 글
  • [Volley][Java]volley로 json데이터받기(3)
  • [안드로이드] extends Fragment 구현시 context 구하는 방법
  • android kotlin - WebView example -안드로이드 코틀린 웹뷰
  • 안드로이드 스튜디오 - GitHub 연동과 add, commit, push 개념
호레
호레
창업 / IT / 육아 / 일상 / 여행
    반응형
  • 호레
    Unique Life
    호레
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 법률
        • 기본
        • 개인정보보호법
        • 정보통신망법
        • 전자금융거래법
        • 전자금융감독규정
        • 신용정보법
        • 온라인투자연계금융업법
      • 창업
        • 외식업 관련
        • 임대업 관련
        • 유통업 관련
        • 세무 관련
        • 마케팅 관련
        • 기타 지식
        • 트렌드
        • Youtube
      • IT기술 관련
        • 모바일
        • 윈도우
        • 리눅스
        • MAC OS
        • 네트워크
        • 빅데이터 관련
        • A.I 인공지능
        • 파이썬_루비 등 언어
        • 쿠버네티스
        • 기타 기술
      • 퍼블릭 클라우드 관련
        • Azure
        • GCP
        • AWS
      • 정보보안 관련
        • QRadar
        • Splunk
        • System
        • Web
      • 기타
        • 세상 모든 정보
        • 서적
      • 게임 관련
        • 유니티
      • 부동산
      • 맛집 찾기
        • 강남역
        • 양재역
        • 판교역
        • ★★★★★
        • ★★★★
        • ★★★
        • ★★
        • ★
      • 결혼_육아 생활
        • 리얼후기
        • 일상
        • 육아
        • 사랑
        • Food
      • 영어
        • 스피킹
        • 문법
        • 팝송
        • 영화
      • K-컨텐츠
        • 드라마
        • 영화
        • 예능
      • 독서
      • 프로젝트 관련 조사
        • 시스템 구축
        • 로그 관련
        • 웹
        • APT
        • 모의 해킹
        • DB
        • 허니팟
        • 수리카타
        • 알고리즘
        • FDS
      • 기업별 구내 식당 평가
        • 한국관광공사
        • KT telecop
        • KT M&S
        • KT powertel
        • KT cs 연수원
        • 진에어
      • 대학 생활
        • 위드윈연구소
        • 진로 고민
        • 채용정보
        • 자동차
        • 주식
        • 악성코드
        • 게임 보안
      • 쉐어하우스
  • 블로그 메뉴

    • 홈
    • 게임 관련
    • IT 기술 관련
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    쥬쥬랜드
    판교역
    맛집
    판교
    유니티
    보안가이드
    수제버거존맛
    돈까스
    수제버거
    이재곧죽습니다
    점심
    수제버거맛집
    복리후생
    판교맛집
    무역전쟁
    런치
    상호관세
    마케팅
    AWS
    대통령
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
호레
안드로이드 WIfiManager 로 주변 wifi 스캔하기! Android WifiManager scan access point wifi list
상단으로

티스토리툴바