Я создаю приложение, которое сканирует доступные сети WI-FI и затем показывает их в списке.вот мой код:
public class MainActivity extends ListActivity {
WifiManager mainWifiObj;
WifiScanReceiver wifiReciever;
ListView list;
String wifis[];
EditText pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=getListView();
mainWifiObj = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
mainWifiObj.startScan();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ssid = ((TextView) view).getText().toString();
connectToWifi(ssid);
Toast.makeText(MainActivity.this,"Wifi SSID : "+ssid,Toast.LENGTH_SHORT).show();
}
});
}
protected void onPause() {
unregisterReceiver(wifiReciever);
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
class WifiScanReceiver extends BroadcastReceiver {
@SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
wifis = new String[wifiScanList.size()];
for(int i = 0; i < wifiScanList.size(); i++){
wifis[i] = ((wifiScanList.get(i)).toString());
}
String filtered[] = new String[wifiScanList.size()];
int counter = 0;
for (String eachWifi : wifis) {
String[] temp = eachWifi.split(",");
filtered[counter] = temp[0].substring(5).trim();//+"\n" + temp[2].substring(12).trim()+"\n" +temp[3].substring(6).trim();//0->SSID, 2->Key Management 3-> Strength
counter++;
}
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,R.id.label, filtered));
}
}
private void finallyConnect(String networkPass, String networkSSID) {
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", networkSSID);
wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);
int netId = mainWifiObj.addNetwork(wifiConfig);
mainWifiObj.disconnect();
mainWifiObj.enableNetwork(netId, true);
mainWifiObj.reconnect();
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"\"" + networkSSID + "\"\"";
conf.preSharedKey = "\"" + networkPass + "\"";
mainWifiObj.addNetwork(conf);
}
private void connectToWifi(final String wifiSSID) {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.connect);
dialog.setTitle("Connect to Network");
TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID1);
Button dialogButton = (Button) dialog.findViewById(R.id.okButton);
pass = (EditText) dialog.findViewById(R.id.textPassword);
textSSID.setText(wifiSSID);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String checkPassword = pass.getText().toString();
finallyConnect(checkPassword, wifiSSID);
dialog.dismiss();
}
});
dialog.show();
}
}
Но во время выполнения на андроид версии Lollipop работает отлично и все.Но на андроид версии KITKAT вылетает и говорит (К сожалению, «Имя приложения» остановилось.).Это происходит при сканировании сетей WI-FI.Я не знаю, что я делаю не так.
Вот мой logcat на андроид KITKAT:
Process: com.example.app, PID: 14212
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS flg=0x4000010 } in com..app.MainActivity$WifiScanReceiver@424b88a0
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:773)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.StringIndexOutOfBoundsException: length=0; index=5
at java.lang.String.indexAndLength(String.java:584)
at java.lang.String.substring(String.java:1449)
at com.example.app.MainActivity$WifiScanReceiver.onReceive(MainActivity.java:83)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:763)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)