why android client new socket command is not working - java

I wrote simple android java client , main activity with socketTask and and a handler in mainactivity. and it doesn't working .
I used debuger and found that the problem is in this line :
this.socket = new Socket(IP_ADDRESS, PORT);
I also had this error massage in the studio :
An unexpected packet was received before the handshake
the server is ok and responding to any other program .
Can some one advice what is the problem . I attaching mainactivity and socket task .
thanks a lot .
main activity
package com.example.app24;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button btnSend ;
TextView tvFromServer;
EditText etToSend;
String strToSend,strFromServer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(this);
etToSend = (EditText) findViewById(R.id.etToSend);
tvFromServer = (TextView) findViewById(R.id.tvFromServer);
tvFromServer = (TextView) findViewById(R.id.tvFromServer);
}
#Override
public void onClick(View v)
{
if (v == btnSend)
{
strToSend = etToSend.getText().toString();
new Thread(new Runnable() {
#Override
public void run() {
SocketTask send1 = new SocketTask(strToSend);
strFromServer=send1.sendReceive();
runOnUiThread(new Runnable() {
public void run() {
tvFromServer.setText(strFromServer);
}
});
}
}).start();
}
}
}
'''
SocketTask.
```
package com.example.newproj;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class SocketTask
{
//private final static String IP_ADDRESS = "172.19.16.179";
private final static String IP_ADDRESS = "192.168.1.124";
private final static int PORT = 8821; // HTTP port
private final static int PACKET_SIZE = 1024; // standard 1kb packet size
private Socket socket;
private String sendingStr="";
private String receivingStr="";
BufferedReader reader;
public SocketTask(String str1)
{
this.sendingStr = str1;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void send()
{
try {
OutputStreamWriter writer = new OutputStreamWriter(this.socket.getOutputStream(), StandardCharsets.UTF_8); // outputStreamWriter creating
writer.write(this.sendingStr);
writer.flush();
Log.d("Result", "sent");
}
catch (Exception e) {
Log.e("Exception", e.toString());
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void receive() {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
char[] charBuffer = new char[1024];
StringBuilder stringBuilder = new StringBuilder();
reader.read(charBuffer);
stringBuilder.append(charBuffer);
reader.close();
receivingStr = stringBuilder.toString();
}
catch (IOException e)
{
Log.e("Exception", e.toString());
}
}
public String sendReceive()
{
try {
this.socket = new Socket(IP_ADDRESS, PORT);
send();
receive();
this.socket.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
return this.receivingStr;
}
}
```

Related

How to connect multiple clients to one host via Wifi P2P

I'm trying to create a WiFiP2P to communicate with 2 android phones and one Raspberry Pi. I want one phone as host and the second phone + Raspberry Pi as clients.
Until know i could create a test APP to connect the 2 phones via Wifi direct (tested successful). I was following a great tutorial on Youtube Wifi P2P. Unfortunately the tutorial just show how to connect one host with one client and not multiple clients.
I was trying to follow the Android developer guide, but I have not enough experience to understand everything.
I hope you guys can help me to understand what I have to change in my code and explain me why.
The following code is the exact copy from the mentioned tutorial.
Here my MainActivity:
package com.example.wifip2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ=1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
initialWork();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_READ:
byte[] readBuff = (byte[])msg.obj;
String tempMsg = new String(readBuff,0,msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
if(mManager!=null) {
mManager.removeGroup(mChannel, null);
}
}else{
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
connectionStatus.setText("Discovery Starting Failed");
}
});
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
final WifiP2pDevice device = deviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"Connected to " + device.deviceName, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = writeMsg.getText().toString();
Toast.makeText(getApplicationContext(),"MSG: " + msg,Toast.LENGTH_SHORT).show();
sendReceive.write(msg.getBytes());
}
});
}
private void initialWork() {
btnOnOff= findViewById(R.id.onOff);
btnDiscover = findViewById(R.id.discover);
btnSend = findViewById(R.id.sendButton);
listView = findViewById(R.id.peerListView);
read_msg_box = findViewById(R.id.readMsg);
connectionStatus = findViewById(R.id.connectionStatus);
writeMsg = findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers)){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for(WifiP2pDevice device : peerList.getDeviceList()){
deviceNameArray[index] = device.deviceAddress;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(getApplicationContext(), "No Devices Found",Toast.LENGTH_SHORT).show();
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;
if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass=new ServerClass();
serverClass.start();
}else if(wifiP2pInfo.groupFormed){
connectionStatus.setText("Client");
clientClass = new ClientClass(groupOwnerAddress);
clientClass.start();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ServerClass extends Thread{
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
// serverSocket= null;
// socket = null;
try {
Log.i("ServerSocket is called", "Called");
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt){
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(socket!=null){
try {
bytes = inputStream.read(buffer);
if(bytes > 0){
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write (byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress){
hostAdd = hostAddress.getHostAddress();
// socket = null;
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here my BroadcastReceiver Class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.nfc.Tag;
import android.util.Log;
import android.widget.Toast;
import static android.content.ContentValues.TAG;
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity)
{
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
if(mManager!=null){
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
Log.d(TAG, "onReceive: P2P peers changed");
}else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
if(mManager==null){
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
}else{
mActivity.connectionStatus.setText("Device Disconnected");
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
//do something
}
}
}

Empty Activity When I try to load JSON from S3

When I navigate to the activity that should load a ListView from a JSON hosted on AWS S3, I get nothing but a blank activity. There's no error message, no errors in the debugger, and Logcat doesn't seem to hold any relevant information.
Here's LoadJSONTask.java:
package com.teamplum.projectapple;
import android.os.AsyncTask;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.teamplum.projectapple.NewsDO;
import com.teamplum.projectapple.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<NewsDO> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Response response) {
if (response != null) {
mListener.onLoaded(response.getAndroid());
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}
and here's MainActivity.java:
package com.teamplum.projectapple;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
//import com.teamplum.projectapple.NewsDO;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoadJSONTask.Listener, AdapterView.OnItemClickListener {
private ListView mListView;
public static final String URL = "https://s3-eu-west-1.amazonaws.com/tyi-work/Work_Experience.json";
private List<HashMap<String, String>> mAndroidMapList = new ArrayList<>();
private static final String KEY_TIT = "title";
private static final String KEY_CAT = "category";
private static final String KEY_DES = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
mListView.setOnItemClickListener(this);
new LoadJSONTask(this).execute(URL);
}
#Override
public void onLoaded(List<NewsDO> androidList) {
for (NewsDO work : androidList) {
HashMap<String, String> map = new HashMap<>();
map.put(KEY_TIT, work.getTitle());
map.put(KEY_CAT, work.getCategory());
map.put(KEY_DES, work.getDescription());
mAndroidMapList.add(map);
}
loadListView();
}
#Override
public void onError() {
Toast.makeText(this, "Error !", Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(this, mAndroidMapList.get(i).get(KEY_TIT),Toast.LENGTH_LONG).show();
}
private void loadListView() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, mAndroidMapList, R.layout.list_item,
new String[] { KEY_CAT, KEY_TIT, KEY_DES },
new int[] { R.id.version,R.id.name, R.id.api });
mListView.setAdapter(adapter);
}
}
I used this tutorial to help make this, if you need any extra information please feel free to ask, thank you.
I have tested the async task for the URL connection and its working fine.
The problem is either on the parsing or on the activity side. Have you tried putting breakpoints and follow the data?

How to import class from another file in java in Android Studio?

I'm trying to call the function getUrlContents(string) inside my seismic_text.java file to my MainActivity.java file. How can I call the function from anywhere in the file? Any information or tip is appreciated. I include my files down below.
This is my MainActivity.java:
package bt.alfaquake;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.NotificationManager;
import android.content.Intent;
import android.view.View;
import android.app.PendingIntent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.NotificationCompat;
import bt.alfaquake.seismic_text;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
}
}
This is my seismic_text.java:
package bt.alfaquake;
import java.net.*;
import java.io.*;
public class seismic_text {
public static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
}
You can call seismic_text.getUrlContents(url); but it will cause NetworkOnMainThreadException
Just wrap this call to Simple AsynkTask.
class MyTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return seismic_text.getUrlContents(url);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO handle result here
}
}
And call it from your code:
new MyTask().execute();
Simply call this in your MainActivty.java:
seismic_text.getUrlContents(url);

Input/Output between C binary and Java on Android

I need to grab text questions from C binary and display it in my TextView. Also, I need to grab an answers from input field and pass it to C binary, etc. I read this topic and tried to run it on Android. C binary works in shell, but my app doesn't work (blank screen). I am very new in Java and I need help.
package com.example.helloapp;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class HelloApp extends Activity
{
private Button btn;
private EditText editText;
private TextView textView;
private BlockingQueue<String> m_queue;
private BufferedReader bufIn;
private InputStream in;
private InputThread inputThread;
private PrintWriter printOut;
private Process p;
private Handler handler;
private String input = null;
// show nice popup on error
private void popup(String msg)
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler()
{
#Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
HelloApp.this.finish();
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
// new Thread cannot change our TextView, so we use Handler
handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
String text = (String) msg.obj;
textView.setText(text);
}
};
File f = new File(getCacheDir()+"/hello");
if(!f.exists())
try {
// unpack our binary...
InputStream is = getAssets().open("hello");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
// ... and make it executable
try {
Process chmod = Runtime.getRuntime().exec("/system/bin/chmod 777 " +f.getPath());
chmod.waitFor();
} catch(IOException e) { popup(e.getMessage()); } catch(InterruptedException e) { popup(e.getMessage()); }
} catch(IOException e) { popup(e.getMessage()); }
try {
p = Runtime.getRuntime().exec(f.getPath());
InputStream in = p.getInputStream() ;
OutputStream out = p.getOutputStream ();
InputStream err = p.getErrorStream();
printOut = new PrintWriter(out);
m_queue = new ArrayBlockingQueue<String>(10);
inputThread = new InputThread(in, m_queue);
inputThread.start();
} catch(Exception e) { popup(e.getMessage()); }
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
editText = (EditText)findViewById(R.id.editText1);
input = editText.getText().toString();
// pass something to C binary
printOut.println(input+"\n");
printOut.flush();
}
});
}
private void setTextHandler(final String text)
{
Message msg = new Message();
msg.obj = text;
handler.sendMessage(msg);
}
private void mainLoop()
{
String line;
while(true)
{
try {
line = bufIn.readLine();
// stdin is always empty... why?
if(line != null) { setTextHandler(line); }
}
catch(IOException e) { popup(e.getMessage()); return; }
}
}
private class InputThread extends Thread
{
InputThread(InputStream in, BlockingQueue<String> queue)
{
bufIn = new BufferedReader(new InputStreamReader(in));
m_queue = queue;
}
public void run() {
try { mainLoop(); }
catch(Throwable t) { popup(t.getMessage()); }
}
}
}
UPDATE: if I compile the following C code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *s;
setvbuf(stdout, NULL, _IONBF, 0); // <<<= disable buffering globally
printf("Enter your name:\n");
fflush(stdout);
scanf("%s", &s);
printf("Hello, %s", s);
fflush(stdout);
return 0;
}
I get results only when binary exits, ie. I run android app, see a blank screen (must see "Enter your name:"), input something, press OK button - binary exits and I get "Enter your name: Hello, Eugene" at once.
PROBLEM SOLVED! See updated C code.

Using TCP + AsyncTask To Keep Connection Open and Listening for Data Being Sent From Server

Hi Stackoverflow members! Heres my issue...
1) Connect To a TCP Server *CHECK
2) Send the Initial Packet & Receive from Server (VB.NET) *CHECK
NOW MY ISSUE
I'm trying to keep my connection alive, and continue to listen for incoming data. I tried using a timer but I had no luck. any help would be highly highly appreciated
package com.WheresmySon;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class TcpClient extends Activity {
private static BufferedReader in;
private static BufferedWriter out;
private static Socket s;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new TcpClientTask().execute();
}
class TcpClientTask extends AsyncTask<Void, Void, Void> {
private static final int TCP_SERVER_PORT = 1234;
private boolean error = false;
Boolean SocketStarted = false;
protected Void doInBackground(Void... arg0) {
try {
s = new Socket("10.0.2.2", TCP_SERVER_PORT);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = "VER:Android,LAT:28.111921,LNG:-81.950433,ID:1038263,SND:0,VDO:0,TXT:Testing";
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine();
Log.i("TcpClient", "received: " + inMsg);
//close connection
} catch (UnknownHostException e) {
error = true;
e.printStackTrace();
} catch (IOException e) {
error = true;
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
if(error) {
// Something bad happened
}
else {
// Success
}
}
}
//replace runTcpClient() at onCreate with this method if you want to run tcp client as a service
private void runTcpClientAsService() {
Intent lIntent = new Intent(this.getApplicationContext(), TcpClientService.class);
this.startService(lIntent);
}
}
TcpClientService.java
package com.WheresmySon;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class TcpClientService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
runTcpClient();
this.stopSelf();
}
private static final int TCP_SERVER_PORT = 1234;
private void runTcpClient() {
try {
Socket s = new Socket("10.0.2.2", TCP_SERVER_PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpClient", "received: " + inMsg);
//close connection
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AsyncTask is not the best place for any network stuff, especially for non-statless connections like Sockets. Best approach is to use Service. You could try to search for any code example about how to use Services to handle socket connection in Android. This code will never works fine.

Categories

Resources