I created a new project with an empty activity, and this is my full code:
MainActivity.java
package com.myapp.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity{
public boolean isConnectedToInternet(){
Runtime runtime = Runtime.getRuntime();
try{
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
}catch (IOException e){
e.printStackTrace();
}
catch(InterruptedException e){
e.printStackTrace();
}
return false;
}
@Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectedToInternet()){
Toast.makeText(this, "connected to internet", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "not connected to internet", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
When I start my application in the emulator, it shows a toast "not connected to internet" - why?
And the internet works on the emulator, I can use chrome in the emulator on the virtual device and it shows youtube.com etc correctly. - It only doesn't work in the application.
What am I missing?