Build error in android socket program in eclipse - java

I have the follwing code to establish a TCP connection between a C server and an android client. The c server works fine. But the following code shows errors on building in eclipse.
package com.app.client.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class my_activity extends Activity
{
private TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
connectSocket("Hello");
}
});
}
private void connectSocket(String a){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 4444);
message = "1";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
while ((in.readLine()) != null) {
txt.append(in.readLine());
}
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
}
}
The errors shown on building is:
main cannot be resolved or is not a field my_activity.java /Androidclient/src/com/app/client/app line 29 Java Problem
What can I do so as to resolve this problem? Thanks in advance.

You need to set up your AndroidManifest.xml within your activity. Find it and add your main activity to it like this:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="my_activity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This will tell the android system that this is your main activity and it should be launched on application start.
If you're new to android, i suggest that you read this

Related

java.net.ConnectException:Failed to connect to /10.0.2.2:443

I am working on an android app that requires user authentication. I am using localhost phpadmin for server and database connexion. The app so far has 1 login activity that imports a php url to connect to localhost. If everything works fine the app is supposed to show an alertDialog saying that login was successful. But whenever i try running the app, when i click login it shows an empty alertDialog and the AndroidStudio debugger shows this error : java.net.ConnectException:Failed to connect to /10.0.2.2:443
This is the code for MainActivity :
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt , PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt= (EditText)findViewById(R.id.editTextTextPersonName);
PasswordEt= (EditText)findViewById(R.id.editTextTextPassword);
}
public void OnLogin(View view) {
String username= UsernameEt.getText().toString();
String password= PasswordEt.getText().toString();
BackroundWorker backroundWorker=new BackroundWorker(this);
String type= "login";
backroundWorker.execute(type,username,password);
}
}
and this is the code for BackroundWorker class:
package com.android.example.meetmev0;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class BackroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
public BackroundWorker ( Context ctx) {
context=ctx;
}
#Override
protected String doInBackground(String... voids) {
String type = voids[0];
String login_url= "https://10.0.2.2/MeetLogin.php";
if(type.equals("login"))
{
String test="so far so good";
try {
String username = voids[1];
String password = voids[2];
URL url= new URL(login_url);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
httpsURLConnection.setRequestMethod("POST");
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);
OutputStream outputStream= httpsURLConnection.getOutputStream();
test= " still good";
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data= URLEncoder.encode("username ", "UTF-8")+"="+URLEncoder.encode(username , "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password , "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpsURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpsURLConnection.disconnect();
Log.v("Activity test: ", result);
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog= new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
using breakpoints i found out that this line OutputStream outputStream= httpsURLConnection.getOutputStream(); is what's throwing the exception.
This is my AndroidManifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.example.meetmev0">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<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"
android:usesCleartextTraffic="true">
<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>
I tried adding ports 80,8080 and 8888 but it didn't work. Swapping 10.0.2.2to localhostor to my local ip didn't work either.
I changed https to http:
String login_url= "https://10.0.2.2/MeetLogin.php" to String login_url= "http://10.0.2.2/MeetLogin.php"
and
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection(); to HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection();
Now it works perfectly.

Android: Connecting to the server

I'm running a simple local server and I just want to watch in terminal if my app is succesfully connected to the server.
Installation and build is succesful, but nothing (by nothing I mean no connection, of course there aren't any data) happens. The server is surely running, the port is set to 8080, my phone is connected to the internet (tried both wifi and data) I'm working with Android Studio, and I added these permissions to my manifest in:
AndroidManifest.xml
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
...
ActivityMain.java
package tlacitko.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view) {
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
URL url = new URL("http://147.32.186.51:8080");
InputStream is = url.openStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(is));
String s = "";
}catch(MalformedURLException ex){
}catch(IOException e){
}
}
});
}
}).start();
}
}

Android Socket Connection Test [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 6 years ago.
I'm trying to test if my Android App is connecting to a Rpi hot spot. I'm following this guide for the client code.
I want to have a toast message pop up depending on the state of socket.isConnected() when I hit a button. However, I think each time I try and implement it, I run into Network on the main thread problems. How could I change the following code to add a simple "if(true), send toast message" using the isConnected method in the onClick?
Thank you for any help!
package mrxhaleenterprise.sockettest;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 39169;
private static final String SERVER_IP = "172.24.1.1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
onClick is called on main Thread.So you are writing to socket(Network Operation) on main thread which is causing problem. Your below code should run on background thread.
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
I want to have a toast message pop up depending on the state of socket.isConnected() when I hit a button.
No you don't. Once you've constructed that Socket, it is connected, and that method won't magically start returning false if the connection goes down. You need to maintain your own state of the connection, depending on whether you've encountered an IOException or end of stream on it. More probably you don't want the button at all, you want to pop up an error dialogue when the disconnect happens.

Can't receive packets on android app

I can't receive any packets on my app. I have a computer running from console-php this script:
$broadcast_string='http://hellokitty/shownumber.html';
$port=2328;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
while(true){
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
sleep(1);
echo "Broadcasting ...\n";
}
on the other hand I got this code running on my phonegap app on the MainActivity.java file:
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.content.Context;
import org.apache.cordova.*;
import java.io.*;
import java.net.*;
import java.util.*;
import android.content.BroadcastReceiver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.content.Context;
import android.app.DialogFragment;
import android.app.AlertDialog;
import android.view.Menu;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.provider.Settings;
import android.view.WindowManager;
import android.util.Log;
import android.content.res.AssetManager;
public class MainActivity extends CordovaActivity
{
public static String URL = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
DatagramSocket socket;
//Wakelock------------------------------------------------------------------------------------------------------------------
WakeLock mWakeLock = null,mPartialWakeLock = null;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// lock used to keep the processor awake.
mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
mPartialWakeLock.acquire();
final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock lock = wifi.createMulticastLock("UDP");
lock.acquire();
//--------------------------------------------------------------------------------------------------------------------------
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
//socket = new DatagramSocket(2328, InetAddress.getByName("0.0.0.0"));
socket = new DatagramSocket(2328);
socket.setBroadcast(true);
URL = null;
while (URL == null) {
System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!");
//Receive a packet
byte[] recvBuf = new byte[12000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
//socket.setSoTimeout(10000);
socket.receive(packet);
//Packet received
System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData()));
String message = new String(packet.getData()).trim();
URL=message;
break;
}
} catch (IOException ex) {
//Nothing
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
while(URL == null){
continue;
}
Log.d("net_discover",URL);
super.loadUrl(URL);
}
}
I've tested the network sniffing packets and traffic it's ok.
I've added the wakelock section since I've read that android blocks broadcast packets, but I'm still not getting anything on my device.
I'm working on a Motorola running Android 4.4.4
On the adb logcat, app is stuck on the msg "Ready to receive.." and that's all I get.
Any suggestions?
UPDATE:
I added code to my app to send packet before starting receiving and for my surprise it does receive it. So I started sending packets and sniffing the network from my computer and I don't see any. So doing some more research I found that the app is working on the lo interface (loopback, 127.0.0.1).
So my question now is, how do I make the app receive packets from wifi interface?

Cannot connect my android device to my python socket server?

I have a python socket server which my android devices are meant to connect to but my android emulator is able to connect to it but my phone is not able to connect to it and gives the error ETIMEDOUT. Can anyone tell what is wrong with it?
Python server:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(10)
while True:
c, addr = s.accept()
print(addr)
c.send(bytes('Thank you for connecting','utf-8'))
c.close()
Android Client:
Client.java:
package com.example.abhishekroul.clientapp;
import android.os.AsyncTask;
import android.widget.TextView;
//import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void,Void,Void>
{
String dstAddress;
int dstPort;
String response="";
TextView textResponse;
Client(String addr,int port, TextView textResponse)
{
dstAddress=addr;
dstPort=port;
this.textResponse=textResponse;
}
#Override
protected Void doInBackground(Void ...arg0)
{
Socket socket=null;
try
{
socket=new Socket(dstAddress,dstPort);
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(1024);
byte[] buffer=new byte[1024];
int bytesRead;
InputStream inputStream= socket.getInputStream();
while((bytesRead=inputStream.read(buffer))!=-1)
{
byteArrayOutputStream.write(buffer,0,bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch(UnknownHostException e)
{
e.printStackTrace();
response="UnknownHostException:"+e.toString();
}
catch (IOException e)
{
e.printStackTrace();
response="IOException:"+e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
textResponse.setText(response);
super.onPostExecute(result);
}
}
MainActivity.java:
package com.example.abhishekroul.clientapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText address, port;
TextView response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = (EditText) findViewById(R.id.address);
port = (EditText) findViewById(R.id.port);
response = (TextView) findViewById(R.id.response);
}
public void funcConnect(View v)
{
Client client= new Client(address.getText().toString(),Integer.parseInt(port.getText().toString()),response);
client.execute();
}
public void funcClear(View v)
{
response.setText("");
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abhishekroul.clientapp" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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>
on emulator its connecting but on an android phone it shows ETIMEDOUT error.
So after lot of testing I have found the solution to the problem by using the port 80 the HTTP protocol which is generally never blocked as HTTP based processes will stop as this port is generally used by this protocol so it is better to user port 80 for socket creation.

Categories

Resources