Android:WIFI开启和关闭应用程序崩溃(JAVA)

时间:2017-08-07 11:11:13

标签: java android

我正在尝试创建一个应用程序来打开和关闭WiFi。我有以下代码。每次我运行它,它都会崩溃。不明白为什么。 API - 26

这是MainActivity.java

package com.example.fahad.test;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

ToggleButton toggleButton;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // setContentView(R.layout.turn_on_off_wifi_programmatically);

    toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

    textView = (TextView) findViewById(R.id.text_view);

    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
            if (checked) {
                textView.setText("WiFi is ON");
                WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                wifi.setWifiEnabled(true);
            } else {
                textView.setText("WiFi is OFF");
                WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                wifi.setWifiEnabled(false);
            }
        }
    });

    if (toggleButton.isChecked()) {
        textView.setText("WiFi is ON");
        WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(true);
    } else {
        textView.setText("WiFi is OFF");
        WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(false);
    }
}
}

请帮助我。感谢

1 个答案:

答案 0 :(得分:0)

只需将此权限添加到您的清单

即可
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />