2016-04-13 20 views
1

Ich möchte die Verbindung zu meinem localhost (oder einer beliebigen URL) testen, ich machte einen einfachen Code zu testen, ich füge die erforderliche Berechtigung zu manifestieren, aber die Funktion immer noch "falsch".Testen der Verbindung zum Server unter Android

hier ist mein Code:

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

import java.net.URL; 
import java.net.URLConnection; 

public class MainActivity extends AppCompatActivity { 
    String adrs = "http://wwww.google.com"; 
    int time = 10000; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     isConnectedToServer(adrs,time); 



     Button button = (Button) findViewById(R.id.btn); 

     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

      if (isConnectedToServer(adrs,time) == true) { Toast.makeText(getBaseContext(),"Connecté !",Toast.LENGTH_LONG).show();} 
       else {Toast.makeText(getBaseContext(),"Connexion perdue",Toast.LENGTH_LONG).show();} 



       isConnectedToServer(adrs,time); 


      } 
     }); 
    } 

    public boolean isConnectedToServer(String url, int timeout) { 
     try{ 
      URL myUrl = new URL(url); 
      URLConnection connection = myUrl.openConnection(); 
      connection.setConnectTimeout(timeout); 
      connection.connect(); 
      Toast.makeText(getBaseContext(),"Connecté !",Toast.LENGTH_LONG).show(); 
      return true; 
     } catch (Exception e) { 
      // Handle your exceptions 
      Toast.makeText(getBaseContext(),"Connexion perdue",Toast.LENGTH_LONG).show(); 
      return false; 
     } 
    } 
} 

und das ist mein Manifest

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.fisher.testconnection"> 
    <uses-permission android:name="android.permission.INTERNET"/> 

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

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

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

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 
+0

verbinden Sie mit dem Internet über einen Proxy? –

+1

Können Sie e.printStackTrace(); im Fangblock? Und füge die Nachricht ein, die du hier bekommst ?? –

+0

entwickeln Sie auf Marshamallow? Dann müssen Sie Laufzeitberechtigungen anfordern – Opiatefuchs

Antwort

2

Tropfen dieser Klasse im Projekt, Änderung url und führen Sie die Aufgabe Netzwerkgeschwindigkeit und den Verbindungsstatus holen von dein Server.

import java.io.IOException; 
import java.math.BigDecimal; 
import java.math.RoundingMode; 
import java.net.MalformedURLException; 
import java.net.URISyntaxException; 
import java.net.URL; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.entity.BufferedHttpEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 

import android.content.Context; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 


public class NetworkSpeedCheckTask extends AsyncTask<Void, Void, String> { 

    private static final int TIMEOUT = 30000; 

    /** 
    * @param networkSped 
    */ 
    public NetworkSpeedCheckTask(TextView networkSped, Context context) { 
     this.networkSped = networkSped; 
     this.context = context; 
    } 

    String linkSpeed3G = "0 Kb/s"; 

    TextView networkSped; 

    private Context context; 

    /** 
    * Before starting background do some work. 
    */ 
    @Override 
    protected void onPreExecute() { 

     if (null != networkSped) 
      networkSped.setText("fetching"); 
    } 

    @Override 
    protected String doInBackground(Void... params) { 

     try { 

      long startTime = System.nanoTime(); 
      HttpGet httpRequest; 
      httpRequest = new HttpGet(new URL("Http://Google.com").toURI()); 

      final HttpParams httpParams = new BasicHttpParams(); 
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT); 

      HttpClient httpClient = new DefaultHttpClient(httpParams); 

      HttpResponse response = (HttpResponse) httpClient.execute(httpRequest); 

      long endTime = System.nanoTime(); 

      HttpEntity entity = response.getEntity(); 

      BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 

      // You can re-check the size of your file 
      final long contentLength = bufHttpEntity.getContentLength(); 

      linkSpeed3G = internetSpeed((endTime - startTime), contentLength, false); 

      // Bandwidth : size(KB)/time(s) 
      float bandwidth = contentLength/((endTime - startTime) * 1000); 

      Log.d("NetworkManger", "-----------[BENCHMARK] Dowload time :" + (endTime - startTime) + " ms"); 

      // Log 
     } catch (MalformedURLException e) { 
      linkSpeed3G = "Failure"; 
      e.printStackTrace(); 
     } catch (URISyntaxException e) { 
      linkSpeed3G = "Failure"; 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      linkSpeed3G = "Failure"; 
      e.printStackTrace(); 
     } catch (IOException e) { 
      linkSpeed3G = "Failure"; 
      e.printStackTrace(); 
     } finally { 
     } 

     return linkSpeed3G; 

    } 

    /** 
    * Update list ui after process finished. 
    */ 
    protected void onPostExecute(String file_url) { 

     if (null != networkSped) { 

      networkSped.setText(linkSpeed3G); 
      if (linkSpeed3G.equalsIgnoreCase("Failure")) { 
       networkSped.setTextColor(0xE43F3F); 
      } else { 
       networkSped.setTextColor(0xff669900); 
      } 

     } 

     Toast.makeText(context, "linkSpeed3G " + linkSpeed3G, 3000).show(); 
    } 

    public static String internetSpeed(long nSecs, long bytes, boolean showBits) { 

     if (nSecs != 0) { 

      BigDecimal secondsBigDecimal = BigDecimal.valueOf(nSecs).divide(BigDecimal.valueOf(1000000000), 2, 
        RoundingMode.HALF_UP); 
      // long secs = nSecs/1000000000; 

      if (showBits) { 
       BigDecimal bitsBigDecimal = BigDecimal.valueOf(bytes * 8); 
       // long bits = bytes * 8; 

       if (secondsBigDecimal.signum() == 1) { 

        // float speed = bits/secs; 
        BigDecimal speeedBigDecimal = bitsBigDecimal.divide(secondsBigDecimal, 2, RoundingMode.HALF_UP); 

        long Kbit = 1024; 
        long Mbit = Kbit * 1024; 
        long Gbit = Mbit * 1024; 

        float speed = speeedBigDecimal.floatValue(); 

        if (speed < Kbit) 
         return String.valueOf(speed) + " bit/Sc"; 
        if (speed > Kbit && speed < Mbit) 
         return String.valueOf(speed/Kbit) + " Kb/S"; 
        if (speed > Mbit && speed < Gbit) 
         return String.valueOf(speed/Mbit) + " Mb/S"; 
        if (speed > Gbit) 
         return String.valueOf(speed/Gbit) + " Gb/S"; 
       } 
       return "???"; 

      } else { 

       BigDecimal bitsBigDecimal = BigDecimal.valueOf(bytes); 
       // long bits = bytes * 8; 

       if (secondsBigDecimal.signum() == 1) { 

        // float speed = bits/secs; 
        BigDecimal speeedBigDecimal = bitsBigDecimal.divide(secondsBigDecimal, 2, RoundingMode.HALF_UP); 

        long Kbit = 1024; 
        long Mbit = Kbit * 1024; 
        long Gbit = Mbit * 1024; 

        float speed = speeedBigDecimal.floatValue(); 

        if (speed < Kbit) 
         return String.valueOf(speed) + " Byte/Sc"; 
        if (speed > Kbit && speed < Mbit) 
         return String.valueOf(speed/Kbit) + " KB/S"; 
        if (speed > Mbit && speed < Gbit) 
         return String.valueOf(speed/Mbit) + " MB/S"; 
        if (speed > Gbit) 
         return String.valueOf(speed/Gbit) + " GB/S"; 
       } 
       return "???"; 

      } 
     } 
     return "###"; 
    } 

} 

Alles was Sie brauchen eine Zeile zu schreiben, um zu überprüfen Server-Konnektivität und Netzwerkgeschwindigkeit

new NetworkSpeedCheckTask(null, getApplicationContext()).execute(); 
+0

Wie kann ich das Timeout einstellen? –

+0

siehe bearbeitete Antwort –

+0

Funktioniert perfekt, danke Mann :)! –

Verwandte Themen