如何在应用程序启动时检测android中的互联网?

时间:2016-02-04 17:49:16

标签: android

我开发了一个完全基于互联网的应用程序。但我在一个点上堆叠。 关键是当用户没有连接到互联网时,应用就停止了。

我使用下面的代码。

public class MainActivity extends ActionBarActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private AdView mAdView;
private InterstitialAd interstitial;
private long lastPressedTime;
static String imgURL = "url";
static String VIDEO_ID = "videoId";
static String TITLE = "title";
static String THUMBNAILS = "img";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();


    isNetworkAvailable();

}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

你应该这样做

boolean isInternet=isNetworkAvailable();

if(isInternet)
{
new DownloadJSON().execute();
}
else
{
//show toast message
}

答案 1 :(得分:0)

// 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;
}

和Manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />