问题描述: 我正在尝试开发一个简单的Android应用程序来强制连接到已存储在手机上的特定开放WiFi配置。
注册广播接收器以监视连接状态。如果连接成功,那么我想打印屏幕上的消息。
在下面的代码片段中,注册的广播接收器是ConnectionReceiver()。执行应用程序时,永远不会打印Toast消息。如果我检查手机wifi设置菜单,设备将连接到wifi网络。
知道为什么代码永远不会进入广播接收器中的if(networkInfo.isConnected()....语句。
我执行了以下检查: 1.确认尝试连接的wifi网络设备是否处于活动状态。 2.确认设备可以在设置菜单中手动连接到设备。 3.运行调试器 - 在toast消息上添加断点并确认正在输入if语句但不显示toast消息。 我还尝试显示活动屏幕,但也没有显示。 5.确认广播接收器已注册。 6.确认清单文件包含以下权限:
<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"/>
知道为什么toast消息没有显示在下面的代码片段中吗?
package com.agt01.wifitest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
public static final String SSID = "vego";
private static final int REQUEST_ENABLE_WIFI = 10;
private static final int TIMEOUT = 20;
private ConnectionReceiver connectionReceiver;
private final ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture taskHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
connectToSpecificNetwork();
} else {
showWifiDisabledDialog();
}
}
private void connectToSpecificNetwork() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(SSID)) {
setContentView(R.layout.activity_conect);
return;
}
else {
List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
if (wifiConfiguration.SSID.equals("\"" + SSID + "\"")) {
connectionReceiver = new ConnectionReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
// setContentView(R.layout.activity_main);
registerReceiver(this.connectionReceiver, intentFilter);
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
//Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID);
wifiManager.reconnect();
break;
}
}
}
}
/**
* Broadcast receiver for connection related events
*/
private class ConnectionReceiver extends BroadcastReceiver {
WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(SSID)) {
setContentView(R.layout.activity_connected);
toast.show();
}
}
}
// User has returned from settings screen. Check if wifi is enabled
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_WIFI && resultCode == 0) {
WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
if (wifi.isWifiEnabled() || wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
connectToSpecificNetwork();
} else {
finish();
}
} else {
finish();
}
}
/**
* Ask user to go to settings and enable wifi
*/
private void showWifiDisabledDialog() {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(getString(R.string.wifi_disabled))
.setPositiveButton(getString(R.string.enable_wifi), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// open settings screen
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(intent, REQUEST_ENABLE_WIFI);
}
})
.setNegativeButton(getString(R.string.exit_app), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
}
答案 0 :(得分:0)
如果即使在输入if语句后也没有显示toast消息,通常它可能是上下文的问题。试试Toast.makeText(getContext(), text, duration)
或Toast.makeText(getApplicationContext(), text, duration)
等。
请检查以下代码,它对我来说非常有效,即它显示了Hello toast!信息。在运行应用程序之前,我已连接到wifi。 (为了测试我改变了if else逻辑)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
public static final String SSID = "SD";
private static final int REQUEST_ENABLE_WIFI = 10;
private static final int TIMEOUT = 20;
private ConnectionReceiver connectionReceiver;
private final ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture taskHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
connectToSpecificNetwork();
} else {
showWifiDisabledDialog();
}
}
private void connectToSpecificNetwork() {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (!networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(SSID)) {
setContentView(R.layout.activity_main);
return;
} else {
List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
if (wifiConfiguration.SSID.equals("\"" + SSID + "\"")) {
connectionReceiver = new ConnectionReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
// setContentView(R.layout.activity_main);
registerReceiver(this.connectionReceiver, intentFilter);
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
//Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID);
wifiManager.reconnect();
break;
}
}
}
}
/**
* Broadcast receiver for connection related events
*/
private class ConnectionReceiver extends BroadcastReceiver {
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(SSID)) {
setContentView(R.layout.activity_main);
toast.show();
}
}
}
// User has returned from settings screen. Check if wifi is enabled
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_WIFI && resultCode == 0) {
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
if (wifi.isWifiEnabled() || wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
connectToSpecificNetwork();
} else {
finish();
}
} else {
finish();
}
}
/**
* Ask user to go to settings and enable wifi
*/
private void showWifiDisabledDialog() {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage("wifi disabled")
.setPositiveButton("enable wifi", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// open settings screen
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(intent, REQUEST_ENABLE_WIFI);
}
})
.setNegativeButton("exit app", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
}