[Q] Connecting From Android Client to Windows Server - Android Software Development

Hi every one, all im trying to do is make it so when you press a button from android it would connect to the server and send a message to servers console saying connected
This is what i have so far
ANDROID CLIENT
Code:
package com.alexandernapoles.shutdown;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SocketClient extends Activity implements Runnable {
private Button ok;
private Socket kkSocket;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button)findViewById(R.id.Button01);
}
public void connectto(){
try {
kkSocket = new Socket("192.168.0.196", 4321);
} catch (UnknownHostException e) {
errorMessage("Unknown host" + "192.168.0.196");
} catch (IOException e) {
errorMessage("Couldn't get I/O for the connection to: " + "192.168.0.196");
}
}
private void errorMessage(String string) {
// TODO Auto-generated method stub
}
@Override
public void run() {
// TODO Auto-generated method stub
}
public void onClick(View src) {
// TODO Auto-generated method stub
switch(src.getId()){
case R.id.Button01:
connectto();
break;
}
}
}
JAVA SERVER
Code:
package main;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server
{
private static ServerSocket sSocket;
public static void main(String args[])
{
try {
sSocket = new ServerSocket(4321,1,InetAddress.getByName("192.168.0.196"));
sSocket.bind(sSocket.getLocalSocketAddress());
boolean listening = true;
while(listening) {
if (sSocket == null) {
sSocket = new ServerSocket(4321,1,InetAddress.getByName("192.168.0.196"));
}
Socket sock = sSocket.accept();
new Thread((Runnable) sock).start();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So far this doesnt work. im lost D:
Please help me.

doesnt work how?
1) windows firewall might block it?
2) android permissions.. did you remember to give your app the internet permissions?

What's not working? It appears from your code that your client is connecting, but that's it. No data is transfered either way.

How do I make it send a message to the server saying it is connected?
Sent from my Samsung Epic 4g.

xsxbluexsx said:
How do I make it send a message to the server saying it is connected?
Sent from my Samsung Epic 4g.
Click to expand...
Click to collapse
You have to wrap your sockets with IOStreams. See:
Socket.getInputStream()
and
Socket.getOutputStream()
at:
http://developer.android.com/reference/java/net/Socket.html
This is really beyond the scope of android development and is a basic concept of Java development in general. Search for a Java tutorial on socket programming and try to get that down before attempting it on the android.

Is there any example you can give me for a client in android
Sent from my Samsung Epic 4g.

This is off the top of my head, but try adding something like this to your connectto() function:
Code:
public void connectto(){
try {
kkSocket = new Socket("192.168.0.196", 4321);
} catch (UnknownHostException e) {
errorMessage("Unknown host" + "192.168.0.196");
} catch (IOException e) {
errorMessage("Couldn't get I/O for the connection to: " + "192.168.0.196");
}
[COLOR="Blue"] String s=new String("Hello World\n");
DataOutputStream out = DataOutputStream(kkSocket.getOutputStream());
out.writeBytes(s);
out.flush();
kkSocket.close();
[/COLOR] }

Related

[Q] How Do I Stop a Media Player

I coded an application that plays a radio stream. The App is very simple just start and stop.
When I press start, the stream plays just fine. But when I call stop, nothing happens.
Here is the code (items in red have been changed to protect the identity of this app ).:
Code:
package [COLOR="red"]com.xxxxxx.stream[/COLOR];
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class [COLOR="red"]NameOfAppActivity[/COLOR] extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("[COLOR="red"]http://xxxxx.xxxxxx.com/stream[/COLOR]");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
setContentView(R.layout.main);
}
private void Stop(){
mp.release();
}
}
I have also tried
Code:
private void Stop(){
mp.stop();
}
}
and
Code:
private void Stop(){
mp.pause();
}
}
Nothing seems to work. I have to force close the app in order to stop it.
What am I doing wrong? Please help.
mp.release() should do it. Have you tried the debugger to make sure that Stop() is being hit? I don't see why it wouldn't, but that's always the first thing I check when things don't behave like I think they should.
Thanks Gene Poole. I will try debugging it when I am home. It's extremely frustrating. I changed the code to:
Code:
private void Stop(){
if (mp != null){
mp.stop();
mp.release();
}
}
Thanks for your input.
Thanks. I figured it out. However. If I hit release, it doesn't play the stream again. The app just FCs. For now I have it set to stop
How did you figure it out?
I see the same behavior.
I/HTTPStream( 194): 1358 Bytes read, progress 64711/65536
Still keeps going, even when I call mediaplayer.stop();
One way that does stop it is to call reset(), but that also hangs for a bit.
Here is the revised code. There is no release in there but I'll figure it out soon.
Code:
package com.xxxxxx.stream;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NameOfAppActivity extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("http://xxxxx.xxxxxx.com/stream");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
private void Stop(){
if (mp != null){
mp.stop();
}
}
The code works fine for the most part. However if I am running the stream and exit the app and comeback to the app, I can not stop it. How do I restore the application's previous state.

[Q] Sockets in Android

SOLVED. please lock.
I have 2 buttons, Server and Client.
The server button contain a textview which prints stuff received from the client.
The client button open Editbox and Send button which uses OnClick function.
In debug mode everything works fine.
When I run them independently and playing with ON/OFF SocketServer and Existing/New SocketClient the program would mostly get stuck and sometimes i get flowed with "Client says: null"
It usually happens when I click in device1 on Server Button, in device2 on client -> send a message from device2 to device1 and it successes -> close server on device1 -> send about 3 messages on device2 (remember that the serverSocket is closed) -> open server on device1 -> close and open client on device2.
The app also getting stuck randomaly after some turn off screen and turn on using the power button while playing with buttons.. and I cant find the issue.
Server.java:
Code:
package com.example.socketproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Server extends Activity
{
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
private final static int SECONDS_TO_WAIT = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
text = (TextView) findViewById(R.id.textview_server);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.server, menu);
return true;
}
@Override
protected void onDestroy()
{
super.onDestroy();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}
@Override
protected void onStop()
{
super.onStop();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}
private class ServerThread implements Runnable
{
public void run()
{
boolean accepted = false;
InetSocketAddress socketAddr = new InetSocketAddress(59135);
try
{
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
serverSocket.bind(socketAddr);
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
while (!Thread.currentThread().isInterrupted())
{
Socket socket = null;
try
{
socket = serverSocket.accept();
accepted = true;
}
catch (InterruptedIOException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
Thread.currentThread().interrupt();
}
if (accepted)
{
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
accepted = false;
}
}
}
private class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
public void run()
{
while (!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
}
}
private class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str)
{
this.msg = str;
}
@Override
public void run()
{
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Client.java:
Code:
package com.example.socketproject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Client extends Activity
{
private final static int SECONDS_TO_WAIT = 5;
private PrintWriter out = null;
private Socket socket = null;
private ClientThread clientThread = new ClientThread();
private String serverIp = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = MY_PHONE_IP_HERE;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
private String getLocalIpAddress()
{
String ipAddr = null;
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress()) )
{
ipAddr = inetAddress.getHostAddress();
return ipAddr;
}
}
}
}
catch (SocketException ex)
{
Log.d(TAG, ex.toString());
}
return ipAddr;
}
public void onClick(View view)
{
try
{
ExecutorService poolExecutor = Executors.newSingleThreadExecutor();
poolExecutor.execute(clientThread);
poolExecutor.shutdown();
poolExecutor.awaitTermination(SECONDS_TO_WAIT, TimeUnit.SECONDS);
EditText et = (EditText) findViewById(R.id.editText_client);
String str = et.getText().toString();
if(out == null)
{
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
}
out.println(str);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (Exception e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
class ClientThread implements Runnable
{
@Override
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIp);
socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, 59135), (int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
//socket = new Socket(serverAddr, 59135);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
// TODO IF HOST ISNT EXIST
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
}
}
EDIT:
nevermind, it was interrupt flag which was erased and made unexpected results with threads. decided to use booleans instead.
Closed at OP's request

Accelerometer Data

I have the code below created but I can not for the life of me figure out how I can send data from the accelerator. I need it to send a constant stream of data until I turn it off. I can't even figure out how to cast the data to a proper variable. Any suggestion would be greatly appreciated.
Code:
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private static final String TAG = "bluetooth1";
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
Button on, off;
float values;
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private UUID MY_UUID = UUID
.fromString(uuid);
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "B0:C4:E7:CF:19:6E";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
acceleration = (TextView) findViewById(R.id.accelText);
off = (Button) findViewById(R.id.bOff);
on = (Button) findViewById(R.id.bOn);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
// On click Listeners
off.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
on.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
// End Onclick Listeners
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e)
{
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume()
{
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try
{
btSocket = createBluetoothSocket(device);
} catch (IOException e1)
{
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try
{
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e)
{
try
{
btSocket.close();
} catch (IOException e2)
{
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try
{
outStream = btSocket.getOutputStream();
} catch (IOException e)
{
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
@Override
public void onPause()
{
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null)
{
try
{
outStream.flush();
} catch (IOException e)
{
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
}
}
try
{
btSocket.close();
} catch (IOException e2)
{
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null)
{
errorExit("Fatal Error", "Bluetooth not supported");
} else
{
if (btAdapter.isEnabled())
{
Log.d(TAG, "...Bluetooth ON...");
} else
{
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try
{
outStream.write(msgBuffer);
} catch (IOException e)
{
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event)
{
// TODO Auto-generated method stub
acceleration.setText("x: " + event.values[0] + "\nY:" + event.values[1]
+ "\nZ:" + event.values[2]);
}
}
NoiseAgent said:
I can not for the life of me figure out how I can send data from the accelerator.
Click to expand...
Click to collapse
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Reply
EmptinessFiller said:
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Click to expand...
Click to collapse
My problem is I am unsure how to send it. How do you actually do that? I don't know what the syntax is to transmit data over bluetooth. The sendData wont work it gives me the error sendData(String) in the type MainActivity is not applicable for the arguments(Sensor)
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
EmptinessFiller said:
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
Click to expand...
Click to collapse
Sweet baby jesus, lord all mighty, thank you.
When I add that to the onSensorChanged I get the error "Cannot make a static reference to the non-static method writeFloat(float) from
the type DataOutputStream" not sure how to clear it up.
Also, I have jumped in way over my head, I really just want to wrap this last bit up and start from scratch. If anyone has a good resource for learning object oriented Java programming and would like to share, that would just be the bees-knees.
Of course java/object oriented programming is necessary.
You have to create an object from the ObjectOutputStream like
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeFloat(...);
...

[Q] Code placement for writing TCP/IP data to TextView

Hello,
I am a first time poster new to Android app development so please bear with me. I am currently working off of two great TCP/IP Client examples. My goal is to create a simple TCP/IP Client that connects to a server and, once a connection is established, continuously updates a TextView with strings passed from the server. If the user presses a button, the client sends a stop command to the server and I would ultimately like to expand the TextView into a graph with the converted string values. I am able to establish the connection to the server and send the stop command from the client but my attempts at adding the read capability have, so far, been unsuccessful with the app crashing as soon as it starts up.
Since it is my first time posting, I am not allowed to link the examples I am using. If anyone is interested in seeing them, however, they are posts from the android-er blog titled: "Android Server/Client example - client side using Socket" and "Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream".
Here is the code in my MainActivity:
Code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textResponse;
TextView textIn;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonStopTest, buttonDisconnect;
Socket socket = null;
DataInputStream incomingString = null;
DataOutputStream terminalLetter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonDisconnect = (Button)findViewById(R.id.disconnect);
buttonStopTest = (Button)findViewById(R.id.stop_test);
textResponse = (TextView)findViewById(R.id.response);
textIn = (TextView)findViewById(R.id.text_in);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonStopTest.setOnClickListener(buttonStopTestOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
//Clicking button (Connect) calls a MyClientTask defined below.
MyClientTask myClientTask = new
MyClientTask(editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}
};
OnClickListener buttonStopTestOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
terminalLetter = new DataOutputStream(socket.getOutputStream());
terminalLetter.writeByte('b');
terminalLetter.writeByte('\n');
terminalLetter.close();
socket.close();
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");
}
}
};
OnClickListener buttonDisconnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String IPaddress;
int Port;
String response = "";
MyClientTask(String addr, int port){
IPaddress = addr;
Port = port;
}
@Override
protected Void doInBackground(Void... arg0) {
//Took socket declaration from here.
try {
//Taking relevant parameters and applying them to socket
socket = new Socket(IPaddress, Port);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
incomingString = new DataInputStream(socket.getInputStream());
textIn.setText(incomingString.readUTF());
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I put the commands for reading data from the server and writing it to the TextView with the code that sets up the connection to the socket. The idea was that it would be the next step after the connection is established but I realize that it looks like I am only reading once. I tried adding a while loop and bringing it out of the doInBackground. In each case, all I got was the whole app crashing on me. It looks fairly straight forward in the example but there the connection is automatic, not triggered and I have not been able to modify the code successfully.
I am still new to Android and this feels like it is an important part of app development so I am hoping someone in the community can help me understand where the section of code relevant to reading data (continuously) should be placed in relation to the rest.
Best,
Yusif Nurizade
P.S. I was going to include the fragment but, since the post is long enough, I chose to omit it. I can share upon request and the logcat.

Radio app into a service

Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
benpaterson said:
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Click to expand...
Click to collapse
You'll have to learn about Android Service and extend that, instead of Activity.

Categories

Resources