所以我的主要目标是制作一个可以在没有任何互联网连接的情况下从一部手机向另一部手机发送消息的应用程序。因此,作为第一步,我尝试创建一个应用程序来打开/关闭 wifi 并显示可用的 wifi 设备。该应用程序似乎在模拟器上运行良好,但在手机上不起作用。即使是基本的 wifi 切换也无法在手机上运行。我附上了我的 MainActivity.java 文件。请帮忙。
MainActivity.java:-
public class MainActivity extends AppCompatActivity {
WifiManager wifiManager;
TextView wifiStatusTextView;
TextView wifiListView;
Switch wifiSwitch;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Defining Variables
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiStatusTextView = (TextView) findViewById(R.id.wifi_status_text_view);
wifiListView = (TextView) findViewById(R.id.wifi_list);
wifiSwitch = (Switch) findViewById(R.id.wifi_switch);
registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
/* Checking wifi state.
* If wifi is enabled, display "wifi is on" and set toggle button to on position.
* If Wifi is disabled, display "wifi is off" and set toggle button to off position.
*/
if (wifiManager.isWifiEnabled()) {
wifiStatusTextView.setText("Wifi is currently ON");
wifiSwitch.setChecked(true);
} else {
wifiStatusTextView.setText("Wifi is currently OFF");
wifiSwitch.setChecked(false);
}
/* adds listener to toggle button
* If toggle is checked, wifi is enabled and "Wifi is on" is displayed.
* If toggle is unchecked, wifi is enabled and "Wifi is off" is displayed.
*/
wifiSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
wifiManager.setWifiEnabled(true);
wifiStatusTextView.setText("Wifi is currently ON");
Toast.makeText(MainActivity.this, "Wifi may take a moment to turn on", Toast.LENGTH_LONG).show();
} else {
wifiManager.setWifiEnabled(false);
wifiStatusTextView.setText("Wifi is currently OFF");
}
}
});
}
@Override
public void onResume()
{
super.onResume();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 87);
}
}
}
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
List<ScanResult> mScanResults = wifiManager.getScanResults();
sb = new StringBuilder();
wifiList = wifiManager.getScanResults();
for (int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ".");
sb.append((wifiList.get(i)).SSID);
sb.append("\n");
}
wifiListView.setText(sb);
}
}
};
}