I'm trying to establish a Bluetooth connection in Android 4.4 but the connect method of BluetoothSocket seems to be working strangely. My app can assume the device is already bonded, so I can connect via MAC address. The thing is that it connects perfectly and immediately the first time the device is bonded, but if I relaunch it, the connection isn't established and a timeout occurs. I do this inside a while loop until it connects, but it takes too long for a real solution or it doesn't work at all. Here's a sample of my code:
public class BluetoothManager{
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket socket;
private OutputStream output;
private InputStream input;
public BluetoothManager() {
/***************/
/* Constructor */
/***************/
// lock = new Object();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public boolean turnOnBluetooth() {
/**************************************/
/* Turn on Bluetooth an notify result */
/**************************************/
// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// enable Bluetooth if not enabled yet
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
while (!bluetoothAdapter.isEnabled()) {
Log.i("Debug", "Waiting for bluetooth to turn on");
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}
public boolean turnOffBluetooth() {
/***************************************/
/* Turn off Bluetooth an notify result */
/***************************************/
// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// disable Bluetooth if not enabled yet
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
}
while (bluetoothAdapter.isEnabled()) {
Log.i("Debug
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}
public boolean configureBluetooth(String MACaddress) {
/***********************************************************************/
/* Configures to the specified bluetooth device and returns the result */
/***********************************************************************/
Log.i("Debug", "Connecting to Bluetooth Device");
bluetoothDevice = bluetoothAdapter.getRemoteDevice(MACaddress);
return (true);
}
#SuppressLint("NewApi")
public void createSocket() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
final UUID serialUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = null;
output = null;
input = null;
Method m = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket)m.invoke(bluetoothDevice, 1);
}
#SuppressLint("NewApi")
public void connect() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
/************************************/
/* Connects to the bluetooth device */
/************************************/
Log.i("Debug", "en connect");
while (!socket.isConnected()) { // we try until the connection is established
try {
socket.connect();
output = socket.getOutputStream();
input = socket.getInputStream();
} catch (IOException e) {
Log.i("Depuración", "Connection not established. Another run : "+e);
try {
Thread.sleep(1000);
} catch (Exception e1) {
}
}
}
}
public void terminateConnection() throws IOException {
Log.i("Debug", "terminating connection");
if(output!=null){
Log.i("Debug", "output!=null - stop streaming");
stopStreaming();
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
if(input!=null){
Log.i("Debug", "input!=null");
input.close();
input=null;
}
if(output!=null){
Log.i("Depuración", "output!=null");
output.close();
output = null;
}
if(socket!=null){
Log.i("Debug", "socket!=null");
socket.close();
socket=null;
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
turnOffBluetooth();
try {
Thread.sleep(100);
} catch (Exception e) {
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.gc();
}
If I call this methods from my MainActivity, it works, but only the first time the device is bonded. If I launch the app again I get an exception trying to connect to the device in:
socket.connect();
I suspect it has something to do with the way I terminate the connection, but I can't figure it out. Here's the sequential call of the methods:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothManager = new BluetoothManager();
try {
bluetoothManager.terminateConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
bluetoothManager.turnOffBluetooth();
bluetoothManager.turnOnBluetooth();
boolean configured = false;
while (!configured) {
Log.i("Debug", "Configuration Attemp");
configured = bluetoothManager.configureBluetooth(MACaddress);
}
Log.i("Debug", "Bluetooth Configured");
try {
bluetoothManager.createSocket();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("Depuración", "Socket created");
try {
bluetoothManager.connect();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Debug", "Connected!!!!");
protected void onPause() {
Log.i("Debug", "On pause");
// TODO Auto-generated method stub
try {
bluetoothManager.terminateConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bluetoothManager = null;
System.gc();
super.onPause();
};
I've been trying to solve this for days and I still can't find a reason.
Well I'm not a Pro on this, but it looks like you should call bluetoothManager.terminateConnection(); when app is closing, lets say onDestroy, but not onCreate; I also had problems to connect, if previous connection was not terminated correctly. just try add this method to your main activity:
#Override
public void onDestroy(){
if (bluetoothManager != null){
bluetoothManager.terminateConnection();
}
super.onDestroy();
}
hope that helps.
Related
I am trying to use sockets in Android to connect over wifi to some UDP port (some_port) on a machine in my local network whose ip is some_ip.
When I run
socket = new Socket(some_ip, some_port);
I get no message error but the program does not seem to read this line and I can't log the error when surrounding with try/catch.
How can I debug that ?
Edit 1 : here's my try/catch
try{
socket = new Socket(some_ip, some_port);
}
catch(ConnectException e) {
e.printStackTrace();
}
Edit 2 : here's the entire code
private void getUDPData() throws IOException {
class ProcessUPDTask extends AsyncTask<String, Void, Socket> {
private Exception exception;
private Socket socket;
public ProcessUPDTask() throws IOException {
}
private void runThread(){
new Thread() {
public void run() {
Toast.makeText(activity, "Own Message", Toast.LENGTH_LONG).show();
}
}.start();
}
protected Socket doInBackground(String... urls) {
try {
try{
socket = new Socket(some_ip, some_port);
socket.setSoTimeout(1500);
}
catch(IOException e) {
e.printStackTrace();
}
Log.d("TAG","this line is reached");
while(true){
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
this.exception = e;
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Socket socket) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
new ProcessUPDTask().execute();
}
Try this
try {
Socket socket = new Socket(IP_ADDRESS, PORT);
socket.setSoTimeout(1500);
} catch (IOException ex) {
Log.e("Connection Error",String.valueOf(ex));
}
Replace your code with this and wait some seconds(60 sec for now) you can see the error toast..
private void getUDPData() throws IOException {
class ProcessUPDTask extends AsyncTask<String, Void, Socket> {
private Exception exception;
private Socket socket;
public ProcessUPDTask() throws IOException {
}
protected Socket doInBackground(String... urls) {
try {
try {
socket = new Socket("192.168.1.101", 1234);
socket.setSoTimeout(1500);
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Reached", Toast.LENGTH_LONG).show();
}
});
while (true) {
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
this.exception = e;
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Socket socket) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
new ProcessUPDTask().execute();
}
You can configure this and use transData() between connectivity.
private void transData(int sending_msg_int) throws IOException {
String sending_msg = Integer.toString(sending_msg_int);
SocketAddress socketAddress = new InetSocketAddress(ip, Data.Port);
DatagramSocket ds = new DatagramSocket();
byte[] buffer = sending_msg.getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
socketAddress);
ds.send(dp);
ds.close();
}
I want show a progress dialog (with a progressbar or circle this is indifferent to me) when i click the button. Actually i can show it but i don't know how hide it after finish the operations inside at onclick. This is the code:
copy.setOnClickListener(new OnClickListener() {
public void onClick(View v){
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
How can i do it?
First define inner class like this in your class
class SaveTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String datafolder = Environment.getDataDirectory()
.getAbsolutePath() + File.separator + "app";
File customfolder = new File(Environment
.getExternalStorageDirectory().getAbsolutePath().toString()
+ File.separator + "BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(
suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}
call this in your onClick() like this..
here we haven't passing any data to AsynchTask so here i am passing null
copy.setOnClickListener(new OnClickListener() {
public void onClick(View v){
SaveTask task = new SaveTask();
task.execute(null, null, null);
}
Start a AsyncTask on onClick method like this:
public void onClick(View v){
YourAsyncTask asyncTask = new AsyncTask(context);
asyncTask.execute();
}
And in your AsyncTask create a ProgressDialog on onPreExecute(), do your stuff in doInBackground() and dismiss the ProgressDialog on onPostExecute():
public class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private Context ctx;
private ProgressDialog progressDialog;
public YourAsyncTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Void res) {
progressDialog.hide();
progressDialog.dismiss();
}
don't foget to declare the progressDialog global variable
#Override
public void onClick(View v) {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
Add progressDialog.dismiss(); in the last line on onClick and in all the catch so that it will disappear even if an Exception is thrown
I'm trying to send an Object from my phone to my PC(Windows) using a TCP socket via WiFi. When I try the same code between two PCs, it works without any error. But when I put the client code to the android device, it fails to send date using writeObject method. But writeUTF command works. It gives the "Software caused connection abort: recv failed" error. Below is the Code. Please help..
Server(in PC):
public class Test {
public static void main(String arg[]) {
ServerSocket serverSocket = null;
Socket socket = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
System.out.println("ip: " + socket.getInetAddress());
Message msg = (Message) in.readObject(); //Message captured from chat client.
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
out.writeObject(new Message("Ack", "Server", "Message Received", "Client"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Client (in Android Device):
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bb=(Button)findViewById(R.id.button1);
bb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Send().execute();
}
});
}
#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;
}
private class Send extends AsyncTask<Void, Void, Void> {
Socket socket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.43.92", 8888); //use the IP address of the server
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
out.writeObject(new Message("Chat", "Server", "Hello World", "Server")); //This method is used to write something to the server.
out.flush();
Message msg = (Message) in.readObject();
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
}
Message(in Both Sides):
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;
public Message(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}
Is the network between the client and server setup properly via your WiFi? Download one of those ping & telnet test apps and use it to test your network connection.
Telnet is a useful TCP debugging app. If you have a server listening on 11.22.33.44 port 1234, you should be able to telnet 11.22.33.44 1234
Maybe, you need to add this functions into Message class:
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(type);
stream.writeObject(sender);
stream.writeObject(content);
stream.writeObject(recipient);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
type = (String) stream.readObject();
sender = (String) stream.readObject();
content = (String) stream.readObject();
recipient = (String) stream.readObject();
}
http://developer.android.com/reference/java/io/Serializable.html
I am working in an online radio streaming project. I play the stream from a url and parsing the sound track info from another json url. All that I did is I repeatedly parse the json after every 10 seconds thats why when the sound track is changing I can get the track info of that specific track. But the json file is being updated 30+ sec before the track changes, thats why sometimes there is a noticeable dissimilarity between the track and the track info.
Here is my asyncTask class where I am playing the stream.
public class RadioPlayer extends AsyncTask<String, Void, Void> {
MediaPlayer mediaPlayer = new MediaPlayer();
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException 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();
}
// might take long! (for buffering, etc)
mediaPlayer.start();
return null;
}
#Override
protected void onPostExecute(Void result) {
}
and here is the handler where I am updating the track info after every 10 seconds:
private void getSongStatistics() {
r = new Runnable() {
public void run() {
try {
title = tsp.parseInitiator();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.i("title", title);
try {
String[] subTitles = title.split("-");
tvTitle.setText(subTitles[1]);
tvArtist.setText(subTitles[0]);
} catch (Exception e) {
tvArtist.setText(title);
}
handler.postDelayed(this, 10000);
}
}
};
handler.postDelayed(r, 10000);
}
Is there any solution by which I may get rid of this weird problem?
Use push instead of polling to update data.
this is my task:to connect PC and mobile phone using socket communication.i have a problem in sending the message i type in the socket connection. i use eclipse to run the program from PC to phone. i type in my text on the textbox. when i press the send button, i could not send the text and let it reflect on the phone. the program codes do not have errors anymore.
this is the link i got for the codes: http://android-er.blogspot.sg/2011/01/simple-communication-using.html
these are my codes with no errors:
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.socket_client);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.217.137.207", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
It seems from the code that you are trying to open a socket connection from your device to external device with given IP [10.217.137.207].
This code should work only if you use the ip of device you are testing it on.
Try to use 127.0.0.1
dataInputStream.readUTF();
will return anything if and only if it is being written from device with IP [10.217.137.207].
If you are using your device's IP address then
dataInputStream.readUTF();
will return all that you write with
dataOutputStream.writeUTF()
I believe it must be clear.