2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Kotlin】wifiをon,offしてみる【AndroidStudio】

Posted at

Design
wifi切り替えボタン一つ配置のシンプルなもの
2019_07_07-003.png

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;
            }
        }
    }
}

実行画面

ファイル名
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?