공감 및 댓글은 포스팅 하는데 아주아주 큰 힘이 됩니다!! 포스팅 내용이 찾아주신 분들께 도움이 되길 바라며 더 깔끔하고 좋은 포스팅을 만들어 나가겠습니다^^
|
이번 포스팅에서는 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를 둘 다 사용했는데요.
그래서
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; } } | 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; } } } | 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> | 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> | 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 을 위한 메서드들 */ } | cs |
코드를 보고 순서대로 따라하시면 큰 어려움 없이 하실 수 있을 거에요^^
이상입니다.
감사합니다.
'안드로이드' 카테고리의 다른 글
안드로이드 코틀린으로 간단한 메모 앱 만들기 (0) | 2018.05.30 |
---|---|
안드로이드 Logcat을 이용해서 로그를 찍어보기! Log 클래스 (0) | 2018.05.17 |
안드로이드 WIfi auto turn on 와이파이 자동으로 활성화시키기 (0) | 2018.05.15 |
안드로이드 레이아웃 width, height 구하기! (0) | 2018.05.10 |
안드로이드 Canvas, Paint 로 좌표에 점 찍기 (0) | 2018.05.09 |