Android App确定是否存在连接

时间:2012-07-06 09:48:42

标签: java android

我想问一个对你们这些人来说可能非常简单的问题。

我怎么知道我的应用程序是否有互联网连接?

我想连接到MySQL数据库,当没有互联网时,应该有一个AlertDialog。

    new AsyncTask() {
        ProgressDialog dialog = ProgressDialog.show(AppActivity.this, "Lade", "Daten werden abgerufen...", true);
        @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.dismiss();
            max = Name.size()-1;
            kontrolle = new boolean [max*2];

            pb.setMax(max/2);

            java.util.Arrays.fill(kontrolle, false);

            bilder();
        }

        @Override
        protected Object doInBackground(Object... arg0) 
        {
            // TODO Auto-generated method stub
               dialog.show();
               getData();
            return null;
        }
    }.execute();

 private void getData() 
{
    String result = "";
    ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

    try
    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://.../read.php");
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        is=entity.getContent();
    }
    catch(Exception e)
    {
        Log.e("log-tag","Keine Verbindung"+e.toString());
        Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
    }

    try
    {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = "";

        while((line= reader.readLine())!=null)
                {
                    sb.append(line+"n");
                }
        is.close();
        result = sb.toString();
         result.trim();
    }
    catch(Exception e)
    {
        Log.e("log-tag","Error"+e.toString());
    }
    try
    {
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++)
        {
            JSONObject json_data = jArray.getJSONObject(i);


            ID.add((String) json_data.get("id"));
            Name.add((String) json_data.get("name"));
            Pts.add((String)json_data.get("pts"));
        }
    }
    catch(Exception e)
    {
        Log.e("log-tag","Error2"+e.toString());
    }
}

我怎样才能实现这一目标?我不知道 我想这个

catch(Exception e)
{
    Log.e("log-tag","Keine Verbindung"+e.toString());
    Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}

会做这项工作,但是当我没有连接时(因为我将我的手机设置为飞行模式),只有一个无尽的ProgressDialog :(

1 个答案:

答案 0 :(得分:1)

正如Jon Taylor所说,这是一个duplicate question

您可以使用以下代码执行此操作

此方法检查移动设备是否连接到互联网并在连接时返回true,如果没有则显示警告框:

private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
AlertDialog.Builder altDialog= new AlertDialog.Builder(this);
altDialog.setMessage("No network connection!");
return false;
} else
return true;
}

将其添加到清单文件

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

编辑:要获取网络类型,您可以使用此代码段:

ConnectivityManager conMan = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);

//mobile
State mobile = conMan.getNetworkInfo(0).getState();

//wifi
State wifi = conMan.getNetworkInfo(1).getState();

然后像这样使用它:

if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}