【Kotlin】wifi를 on, off 해 본다【AndroidStudio】

디자인
wifi 전환 버튼 하나 배치의 간단한 것


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.wifitoggle">

    <!-- wifiの操作権限 -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.kt
package com.example.wifitoggle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.net.wifi.WifiManager

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val wifiManager : WifiManager = getApplicationContext().getSystemService(WIFI_SERVICE)as WifiManager


        val toastButton: Button = findViewById(R.id.button_01)
        toastButton.setOnClickListener {

            if (wifiManager.isWifiEnabled) {
                Toast.makeText(this, "wifiオフ", Toast.LENGTH_SHORT).show()
                wifiManager.isWifiEnabled = false;
            } else {
                Toast.makeText(this, "wifiオン", Toast.LENGTH_SHORT).show()
                wifiManager.isWifiEnabled = true;
            }
        }
    }
}


실행 화면

좋은 웹페이지 즐겨찾기