WIFIデータの状態のON/OFFと状況確認、テザリング確認

2014年6月14日土曜日

android ネットワーク 開発

t f B! P L
WIFI、テザリングのON/OFFの変更と、今のON/OFFの確認を行うプログラムです。
使用方法は、
初期化
 WifiData wifiData = new WifiData(getApplicationContext());

ON/OFF変更
 wifiData.setEnabled(true or false);

ON/OFF状態確認
 wifiData.isEnabled();

実際の接続状態
 wifiData.isConnect();

テザリングのON/OFF変更
 wifiData.setTetheringEnabled(true or false);

テザリングON/OFF状態確認
 wifiData.isTetheringEnabled();

という感じです。たぶん、android2.3.3以降なら動作すると思います。

ソース
######################################################################
public class WifiData extends Service
{
protected WifiManager mWifiManager;
protected Context myContext;

WifiData(Context context)
{
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
myContext = context;
}

// wifi状態確認
// ON:true
// OFF:false
protected boolean isEnabled()
{
final boolean state = mWifiManager.isWifiEnabled();
return state;
}

// wifi接続状態確認
// ON:true
// OFF:false
protected boolean isConnect()
{
boolean state;

// システムから接続情報をとってくる
final ConnectivityManager conManage = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

// wifiの接続状態を取得
final State wifiState = conManage.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

if(State.CONNECTED == wifiState){
state = false;
}else{
state = true;
}
return state;
}

// wifi状態設定
protected void setEnabled(boolean isChecked)
{
// wifi設定を変更
mWifiManager.setWifiEnabled(isChecked);
}

// テザリング設定
protected void setTetheringEnabled(boolean flag)
{
try
{
   Method method = mWifiManager.getClass().getMethod(
    "setWifiApEnabled",WifiConfiguration.class, boolean.class);
   //テザリングの設定
   method.invoke(mWifiManager, null, flag);
}
catch (Exception e)
{
   e.printStackTrace();
}
}

// テザリングON/OFF確認
protected boolean isTetheringEnabled()
{
boolean status = false;
try
{
Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
if ("true".equals(method.invoke(mWifiManager).toString()))
{
status = true;
}
else
{
status = false;
}
}
catch (Exception e)
{
// たぶんここに行くときはアンサポートの場合
e.printStackTrace();
}
return status;
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

}

QooQ