I am working on an Android Studio project with several activities. I am currently trying to read the output from a Java Servlet on localhost but it seems to be crashing due to a socket permission.
I've made a new project, used the exact same code and worked perfectly. So I dont understand why is not willing to work on my project.
public class LoginActivity extends AppCompatActivity {
String apiUrl = "http://10.0.2.2:8080/ProyectService/Servlet?action=login";
EditText username;
EditText password;
AlertDialog dialog;
Usuario session;
@Override
public void onCreate(Bundle savedInstanceState) {
// Inicializacion de ventana
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
// Inicializacion de componentes
username = findViewById(R.id.username);
password = findViewById(R.id.password);
// Inicializacion de funcionalidad de botones
Button button= (Button) findViewById(R.id.login);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
UserLoginTask mAuthTask = new UserLoginTask();
mAuthTask.execute();
}
});
password = findViewById(R.id.password);
createAlertDialog("Usuario o Contraseña Incorrectos");
}
private void createAlertDialog(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setTitle("Error");
dialog = builder.create();
}
// ASYNCRONUS NETWORK PROCESS
public class UserLoginTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
System.out.println(apiUrl);
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
//System.out.print(current);
}
System.out.print(current);
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
}
protected void onPostExecute(String success) {
Log.i(success, "");
//attemptLogin();
}
}
I Expect it to read the data but it crashes at this line:
InputStream in = urlConnection.getInputStream();
This is the error output:
java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:114)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:93)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
First of all you need change your android manifest .xml But after this action you must uninstall application and run it again. https://developer.android.com/training/basics/network-ops/connecting
and code here:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in AndroidManifest.xml
I had to uninstall the app from the emulator and then everything started to work. I just needed the folowing permission on the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Just uninstall the app from the emulator then run again and it’ll work. I had the same issue
To uninstall the app run your project when "the application had stopped" message appear click "app info" then uninstall.
If anyone still has this issue I encountered it when I used VPN and tried to connect to wifi while cellular was on. I was using Anyconnect VPN client. Solution is to enable the allow bypass that will let you bind a socket to a specific network if this is what you are looking for.
AnyConnect only uses allowBypass if it's configured in its managed restrictions (by EMM), via this key: vpn_connection_allow_bypass.
Solved: All I needed to do was to uninstall the app from the emulator or physical connected device and run it again.
Set android:usesCleartextTraffic="true" in the manifest file.
Add the permission INTERNET.
Uninstall app and then install again.
I had to delete this
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and keep this
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" />
Set android:usesCleartextTraffic="true" in the manifest file. Add the permission INTERNET. Uninstall app and then install again.its work to me
I had the same issue in android emulator, even after adding
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
and
android:usesCleartextTraffic="true"
and reinstalling the app still had the issue on my emulator.
AVD Manager -> Right click -> Cold Boot now
solved my issue, looks like if we ran the app initially without adding internet permissions / clearTextTraffic we might need to cold boot as it store some cache.
If you forgot to add <uses-permission android:name="android.permission.INTERNET" /> to your Manifest.xml, do it now
If you already added it but the error persists, uninstall the app first then run i again.
More often than not I run into the same issue because I forgot <uses-permission android:name="android.permission.INTERNET" /> in my first installation.
The OS thought the app doesn't need Internet permission (which is dumb IMO) and would not check any permission update to the app (which is even dumber IMO).
The only way to tell the Android OS to check your updated permission requests is to uninstall the app first before installing again.
I think neither
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />android:usesCleartextTraffic="true"
really matters hereIf you are using a localhost server on your Mac then use the local IP address that is assigned for your machine as your API address. i.e. 192.168.x.x (find it in Settings -> Network) not localhost nor 127.0.0.1.
As they mentioned above, uninstall the app and then put these tags in your manifest:
in the application section:
android:usesCleartextTraffic="true"
Then in your manifest section:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.a.myapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I am a little late to this but I encountered this problem and I found out that android:usesCleartextTraffic requires minimum API version of 23. Therefore, in the module gradle build file, switch the minimum version to 23 and it should work.
Working solution.