[embedyt] https://www.youtube.com/watch?v=5u_OlpE81p0[/embedyt]
AndroidManifest.xmlactivity_main.xmlMainActivity.java
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.codinginflow.togglewifiexample"> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_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>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context="com.codinginflow.togglewifiexample.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="enableWifi" android:text="Wifi ON" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="disableWifi" android:text="Wifi OFF" /> </LinearLayout>
package com.codinginflow.togglewifiexample; import android.content.Context; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { private WifiManager wifiManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); } public void enableWifi(View v) { wifiManager.setWifiEnabled(true); } public void disableWifi(View v) { wifiManager.setWifiEnabled(false); } }