首先我提示用户打开wifi。 我想打开wifi,如果关闭,扫描所有可用的无线网络,并根据它的ssid连接到某个。 我想注册一个广播接收器,等到WifiManager完成扫描结果。
public class Project1 extends Activity {
/**
* Called when the activity is first created.
*/
EditText userName;
EditText passWord;
Button button;
TextView thankYou;
WifiManager wifiManager;
List<ScanResult> results1;
BroadcastReceiver receiver;
public Boolean connectToNetworK() {
Log.e("Start of connect","Debug");
Log.e("before wifi manager of connect","Debug");
if(!wifiManager.isWifiEnabled()){
Log.e("wifi is not enabled","Debug");
wifiManager.setWifiEnabled(true);
}
Log.e("after wifi manager of connect","Debug");
List<ScanResult>results =null;
Log.e("after scan result = null","Debug");
while(!wifiManager.isWifiEnabled())
{
Log.e("wifi still off","Debug");
}
Log.e("wifi is on","Debug");
Log.e("starting scan","Debug");
wifiManager.startScan();
Log.e("waiting","Debug");
if(results1!=null && !results1.isEmpty())
{
Log.e("Results1 is not emplty","Debug");
}
}
@Override
public void onStop()
{
unregisterReceiver(receiver);
}
public void onCreate(Bundle savedInstanceState) {
final Context contex = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(receiver == null){
Log.e("Registering reciver","mark");
receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
Log.e("In broad cast reciver","mark");
results1 =wifiManager.getScanResults();
}
};
registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
}
if (!mWifi.isConnected()) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Open the Wifi");
alert.setMessage("Your Wifi is Currently Turned off, Would You like to turn it on?");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(connectToMobinilNetworK())
{
AfterWifiIsOn();
}
else{
Intent intent = new Intent(contex, ErrorPage.class);
startActivity(intent);}
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(contex, ErrorPage.class);
startActivity(intent);
}
});
alert.show();
} }
}
}
The list of scan resutls are always empty and the logs inside the broadcast receiver is not written.
Thanks in advance.
答案 0 :(得分:0)
您是否在AndroidManifest中设置了正确的权限?根据{{3}},您的权限应如下所示:
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />