在我的android应用程序中,我正在创建(代码如下所示)应用程序加载时的热点(访问点),用于某些目的,必须在应用程序的整个生命周期中保持活动状态(我知道它有一些缺点) ),现在,我怎样才能确保它始终保持活跃状态?我唯一的想法是运行一个计时器,它检查method.getName()。equals(“setWifiApEnabled”)状态并确定它是否处于非活动状态?当AP被禁用时,是否有更好的方法来获得一些指示?
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.EXTRA_NEW_STATE);
filter.addAction(WifiManager.EXTRA_SUPPLICANT_CONNECTED);
registerReceiver(wifiEventReceiver, filter);
private BroadcastReceiver wifiEventReceiver = new BroadcastReceiver() {
private boolean enabled = false;
@Override
public void onReceive(Context context, Intent intent) {
System.out.println ("WiFi Event BroadReceiver:onReceive()=======================================");
if(intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
System.out.println("===== SUPPLICANT_STATE_CHANGE_ACTION event happened....");
intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
}
}
};
private void createWifiAccessPoint() {
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods(); //Get all declared methods in WifiManager class
boolean methodFound=false;
for(Method method: wmMethods){
if(method.getName().equals("setWifiApEnabled")){
methodFound=true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = ssid;
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
try {
boolean apstatus=(Boolean) method.invoke(wifiManager, netConfig,true);
for (Method isWifiApEnabledmethod: wmMethods)
{
if(isWifiApEnabledmethod.getName().equals("isWifiApEnabled")){
while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){
};
for(Method method1: wmMethods){
if(method1.getName().equals("getWifiApState")){
int apstate;
apstate=(Integer)method1.invoke(wifiManager);
}
}
}
}
if(apstatus)
{
Log.d("Splash Activity", "Access Point created");
}else
{
Log.d("Splash Activity", "Access Point creation failed");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if(!methodFound){
Log.d("Splash Activity", "Your phone's API does not contain setWifiApEnabled method to configure an access point");
}
}
答案 0 :(得分:0)
您似乎必须为SUPPLICANT_STATE_CHANGED_ACTION 或SUPPLICANT_CONNECTION_CHANGE_ACTION
注册BroadcastReceiver
我假设你知道注册接收器。
答案 1 :(得分:0)
鉴于无法保证 WiFi连接,目前尚不清楚您要在此处实现的目标。你能做的最好的事情就是如果失败就“优雅地”失败。
要监控WiFi网络的状态,您需要为NETWORK_STATE_CHANGED_ACTION注册一个监听器。忘掉suppliant state。
要保持WiFi无线电状态清醒,请使用WiFiLock。
答案 2 :(得分:0)
我认为您可以建立TCP连接并检查其状态,或者您可以发送UDP数据包并检查其状态。