蔭試圖建立連接到網絡服務器和retricve數據的應用, 我想要做一些功能如何檢查互聯網訪問在android中啓用?
- 當我點擊我的應用程序,首先檢查網絡連接是否已啓用? 如果它啓用它啓動應用程序,否則打開互聯網訪問設置...之後,它重定向到我的應用程序....
- 當應用程序連接到網絡服務器,連接超時後特定時間如果連接不成功。
蔭試圖建立連接到網絡服務器和retricve數據的應用, 我想要做一些功能如何檢查互聯網訪問在android中啓用?
在我的一個應用程序中,我有一個類Defin編這樣的:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
而且在我需要檢查連接狀態的活動,我用這個:
// DEFINE THIS AS A GLOBAL VARIABLE
AlertDialogManager alert = new AlertDialogManager();
在onCreate()
:
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
哦。差點忘了。如果您還需要將用戶重新定向到設置面板,激活互聯網上,你可以使用一個意圖是這樣的:
您可能會促使在AlertDialog用戶,並讓他們選擇,如果他們想。如果是的話,運行這段代碼。
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(intent);
編輯:
我錯過了明顯(Commonsware指出,一出在他的評論)。
您需要將ACCESS_NETWORK_STATE權限添加到您的Manifest文件。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
這是我用它來檢查網絡連接
// Checks Internet Status
public boolean isOnline() {
if(cm == null)
return false;
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED)
return true;
return false;
}
而且這個權限添加到您的清單文件中的函數
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
要用戶發送到WiFi設置頁面使用
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
如果網絡不可用如何重定向到網絡設置選項? – 2013-02-17 14:41:14
非常感謝你先生艾邁德永旺Axan – 2013-02-17 14:44:43
你最歡迎 – 2013-02-17 14:46:01
您可以使用此方法:
public boolean isConn() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity.getActiveNetworkInfo() != null) {
if (connectivity.getActiveNetworkInfo().isConnected())
return true;
}
return false;
}
並添加此權限清單文件:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
thanx爲您的答案Siddharth – 2013-02-17 14:43:07
@Sibinfrancis:很高興有幫助。 :-) – 2013-02-17 14:49:36
請注意,這需要'ACCESS_NETWORK_STATE'權限,最後我檢查。它也不會「檢查互聯網訪問在Android中啓用」 - 它檢查是否有活動的網絡。此代碼中沒有任何內容確認網絡可以訪問Internet上的任何主機(例如防火牆規則)。 – CommonsWare 2013-02-17 15:44:01