I want to test the connection to my localhost ( or any URL ) , i made a simple code to test, i add the needed permission to manifest , but the fonction still returning "false".
here's my 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;
}
}
}
and this is my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
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>
Aucun commentaire:
Enregistrer un commentaire