Sending strings over UDP socket - android

I am trying to make my test application send strings through a UDP socket. It keeps on throwing AndroidRuntime error on line soc.send(pac);. I already have required permissions set in the android_manifest file.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
String text= editText1.toString();
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
udpmsg(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void udpmsg(String text) throws java.io.IOException
{
InetAddress to = InetAddress.getByName("192.168.0.105");
int port=55505;
DatagramSocket soc = new DatagramSocket();
byte[] data = text.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
soc.send(pac);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Please note that the send method of DatagramSocket can also throw java.lang.SecurityException which is a runtime exception and you're not catching it anywhere in your code.
As a quick check, replace catch (IOException e) { with catch (Exception e) { and tell us what is displayed in the log after this modification.

Related

Starting new Thread freezes UI

I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.

App crashes after sending a message using sockets

I'm developing a simple chat app and it just stops after transmitting the message. The Server shows the message that means that it is sent successfully but my app crashes after that. This is the Client code :
package com.example.androidpc;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Chat extends Activity {
Socket socket;
EditText msg_txt;
TextView chatfield_tv;
Button send_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
msg_txt = (EditText) findViewById(R.id.msg_txt);
chatfield_tv = (TextView) findViewById(R.id.chatfield_tv);
send_btn = (Button) findViewById(R.id.send_btn);
socket = SocketWrapper.getSocket();
send_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new chatIO().execute();
}
});
}
private class chatIO extends AsyncTask<String,String,String>{
PrintStream ps;
Scanner scan;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
ps = new PrintStream(socket.getOutputStream());
ps.println(msg_txt.getText().toString());
publishProgress("you");
scan = new Scanner(socket.getInputStream());
publishProgress("i");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
if(values[0].equals("you"))
{
chatfield_tv.append("You : "+msg_txt.getText().toString());
msg_txt.setText("");
}
else
{
chatfield_tv.append("Server : "+scan.nextLine());
}
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
ps.flush();
scan.close();
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Streaming Audio Android app doesn't works on Galaxy S4

I've created an app (radio streaming) but doesn't works on S4.
I've tested this app on my Galaxy Nexus, Xperia Arc s, Htc Desire and it works properly.
I think there is an error in my code.
My code:
package com.dieesoft.radiolluvia;
import java.io.IOException;
import android.R.array;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.TrackInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
private ProgressDialog pb;
private Button bplay;
private Button bstop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bplay = (Button) findViewById(R.id.button1);
bstop = (Button) findViewById(R.id.button2);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
bplay.setOnClickListener(this);
bstop.setOnClickListener(this);
}
#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 onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.button1 )
{
//button play
new iniciarStreaming().execute();
Toast.makeText(this, "Play", Toast.LENGTH_SHORT).show();
}
else if(v.getId() == R.id.button2)
{
//button stop
Toast.makeText(this, "Stop", Toast.LENGTH_SHORT).show();
mp.stop();
}
}
private class iniciarStreaming extends AsyncTask<Void, Void, Boolean> implements OnPreparedListener
{
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
mp.setDataSource("http://makrodigital.com:8134/radiolluvia");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.prepareAsync();
mp.setOnPreparedListener(this);
return null;
}
protected void onPreExecute() {
// TODO Auto-generated method stub
pb = new ProgressDialog(MainActivity.this);
pb.setMessage("Buffering...");
pb.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
if (pb.isShowing()) {
pb.cancel();
}
mp.start();
}
}
Your streaming url (http://makrodigital.com:8134/radiolluvia) has AAC format with content-type: audio/aacp.
But audio/aacp streaming is not supported directly. Maybe previously was another link? MP3 or something else?
For playing this url you can use this library:
http://code.google.com/p/aacplayer-android/

Can't send an SMS between 2 emulators

My project is about communication between 2 phones, on which the app will be installed.
The communication is an SMS communication, each SMS contains data and the receiving device must interpret it and sort in specified ListViews.
The project contains classes of: Send Data Form and class of 3 ListViews displaying the received data.
My problem is , that I'm not sure If my sms is sent(Because a dialog window does not appear after clicking the send button. Moreover, on the second emulator there is no indication whenever there is an incoming SMS message.
Send Data Form:
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AddContactDeatils extends Activity implements OnClickListener {
Button sendToParallel, sendToParallel2;
TextView nameT, idT, phoneT;
EditText nameF, idF, phoneF;
int recipient;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact_form);
sendToParallel=(Button)findViewById(R.id.sendToParallel);
sendToParallel.setOnClickListener(this);
sendToParallel2=(Button)findViewById(R.id.sendToParallel2);
sendToParallel2.setOnClickListener(this);
nameT=(TextView)findViewById(R.id.nameTitle);
idT=(TextView)findViewById(R.id.idTitle);
phoneT=(TextView)findViewById(R.id.phoneTitle);
nameF=(EditText)findViewById(R.id.nameField);
idF=(EditText)findViewById(R.id.idField);
phoneF=(EditText)findViewById(R.id.phoneField);
}
protected void sendSms(String phoneNumber, String message) {
// TODO Auto-generated method stub
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
public void checkRecipient(EditText et)
{
try {
recipient=Integer.parseInt(et.toString());
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(this, "Only numbers are allowed", Toast.LENGTH_LONG).show();
et.setText("");
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
String message = null;
String name=nameF.toString();
message+=name+";";
String idTxt=idF.toString();
message+=idTxt+";";
String phone=phoneF.toString();
message+=phone;
switch(id)
{
case R.id.sendToParallel:
{
sendSms("5554", message) ;
break;
}
case R.id.sendToParallel2:
{
sendSms("5556", message) ;
break;
}
}
}
}
3 ListViews Displaying recieved data
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DataLists extends Activity implements OnClickListener {
ListView idList, namesList, phonesList;
MyReciever mr;
ArrayList<String>ids= new ArrayList<String>();
ArrayList<String>names=new ArrayList<String>();
ArrayList<String>phones=new ArrayList<String>();
ArrayAdapter<String> idAdapter, namesAdapter, phonesAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details_lists);
idList=(ListView)findViewById(R.id.idList);
namesList=(ListView)findViewById(R.id.namesList);
phonesList=(ListView)findViewById(R.id.phonesList);
idAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,ids );
idList.setAdapter(idAdapter);
namesAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
namesList.setAdapter(namesAdapter);
phonesAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, phones);
phonesList.setAdapter(phonesAdapter);
}
public void addItemToIdList(String st)
{
ids.add(st);
idAdapter.notifyDataSetChanged();
}
public void addItemToNamesList(String st)
{
names.add(st);
namesAdapter.notifyDataSetChanged();
}
public void addItemToPhonesList(String st)
{
phones.add(st);
phonesAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private class MyReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle=intent.getExtras();
SmsMessage[]msgs=null;
if(bundle!=null)
{
Object[]pdus=(Object[]) bundle.get("pdus");
msgs=new SmsMessage[pdus.length];
for(int i=0;i<msgs.length;i++)
{
int index=0, prev=0;
String msgBody=msgs[i].getMessageBody().toString();
index=msgBody.indexOf(';');
prev=index;
String name=msgBody.substring(0, index);
addItemToNamesList(name);
msgBody=msgBody.substring(index+1);
index=msgBody.indexOf(';');
String id=msgBody.substring(prev, index);
addItemToIdList(id);
msgBody=msgBody.substring(index+1);
String phone=msgBody;
addItemToPhonesList(phone);
}
}
}
}
}
Add Pemissions for Send and Recive SMS
<uses-permission android:name="android.permission.SEND_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" >
</uses-permission>
and Run Two Emulator for Send Sms.. eg 5554 to 5556

threads to AsyncTask( android, Modbus/TCP)

I'm working a connection to a PLC via TCP / Modbus and Jamod library, therefore I use and work with threads. I'm using to handle AsyncTask thread function, but when running my code the application is not responding and closes automatically. Thanks for the help in advance =)
package com.JR.scada;
import java.net.InetAddress;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.net.TCPMasterConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity{
TextView text, depurar;
EditText IP;
Button boton;
TCPMasterConnection con = null; //the TCP connection
ModbusTCPTransaction trans = null; //the Modbus transaction
InetAddress addr = null; //direccion del esclavo
int port = Modbus.DEFAULT_PORT;//puerto por defecto 502
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.lblRegistro);
IP = (EditText) findViewById(R.id.txtIp);
depurar = (TextView) findViewById(R.id.txtdepurar);
boton = (Button)findViewById(R.id.btnVerRegistro);
}
#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
protected void onStop() {
super.onStop();
//Close the TCP connection
con.close();
}
public class conectar extends AsyncTask<String,String,Integer>{
protected Integer doInBackground(String... urls) {
try {
text.setText("Entro en el try");
//IP address;
addr = InetAddress.getByName("212.170.50.238");
// Open the connection
con = new TCPMasterConnection(addr);
con.setPort(port);
con.connect ();
} catch (Exception e) {
Log.d("MODBUS","connection error", e);
depurar.setText("no conecta");
return 1;
}
return 0;
}
protected void onPostExecute(Integer bytes) {
depurar.setText("conecta");
}
}
public void onClick(View v) {
conectar conectamos = new conectar();
conectamos.execute("hola");
}
see any errors?
We can't touch UI during onBackground()
depurar.setText("no conecta");
Use UI thread or put it on onPost().

Categories

Resources