Android UI from other thread - java

I'm creating an application that gets the get the homestatus from a server in json but this happens on another thread. this isn't a problem when i try to set most Items on the ui because i can set them in a static void. but when i try to create a new switch and space i can't call 'this' to create a new.
code for getting the homestatus:
public void loadHomeStatus()
{
if(socket != null) {`enter code here`
if (socket.isConnected()) {
Log.d("BtnUpdate","already connected");
return;
}
}
swAlarm = (Switch) findViewById(R.id.swAlarmState);
tvTemperature = (TextView) findViewById(R.id.tvTemprateur);
tvHumidity = (TextView) findViewById(R.id.tvHumidity);
llDevices = (LinearLayout) findViewById(R.id.llDevices);
new Thread() {
public void run() {
try
{
busyConnecting = true;
Log.d("loadHomeStatus","trying to connect to: " + host + ":" + port);
socket = new Socket(host, port);
uiConnected();
Log.d("loadHomeStatus","Connected");
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
DataInputStream is = new DataInputStream(socket.getInputStream());
os.writeBytes(password);
Log.d("Connect", "send: " + password);
while (socket.isConnected()) {
byte[] data = new byte[500];
int count = is.read(data);
String recieved = new String(data).trim();
Log.d("loadHomeStatus","recieved " + recieved );
if(recieved.toLowerCase() == "failed")
{
Log.d("loadHomeStatus","failed to log in");
}
else
{
try
{
homeStatus = new Gson().fromJson(recieved, HomeStatus.class);
uiLoadStatus();
} catch (Exception e)
{
Log.d("Error", e.toString());
}
}
}//end of while loop
Log.w("loadHomeStatus", "end connection thread ");
//ends thread
Thread.currentThread().interrupt();
return;
}
catch (UnknownHostException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
catch (IOException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
Log.w("loadHomeStatus","Connection ended");
socket = null;
busyConnecting = false;
uiDisconnected();
}
}.start();
}`
Code for setting ui
public static void uiLoadStatus()
{
if (homeStatus != null)
{
try {
tvTemperature.post(new Runnable()
{
public void run()
{
//Log.d("uiLoadStatus to string",homeStatus.toString());
tvTemperature.setText(homeStatus.temperature + "°C");
tvHumidity.setText(homeStatus.humidity + "%");
}
});
}
catch(Exception e)
{
Log.d("uiLoadStatus status fragment", e.toString());
}
try {
swAlarm.post(new Runnable()
{
public void run() {
swAlarm.setChecked(homeStatus.alarmState);
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
try {
llDevices.post(new Runnable()
{
public void run() {
uiLoadDevices(); //this gives and error because it's not static
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
public void uiLoadDevices()
{
for (int i = 0; i < homeStatus.lstDevices.size(); i++) {
String deviceAdd = homeStatus.lstDevices.get(i);
Space mySpace = new Space(this);
Switch mySwitch = new Switch(this);
mySpace.setMinimumHeight(50);
mySwitch.setText(homeStatus.getName(deviceAdd));
mySwitch.setChecked(homeStatus.getState(deviceAdd));
mySwitch.setTextSize(18);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.LEFT;
llDevices.addView(mySpace, lp);
llDevices.addView(mySwitch, lp);
}
}

You should use AsyncTask and put the network interaction part in the doInBackground() method. To update the UI components, implement those logics in the onPostExecute() method

uiLoadStatus is a static method (not sure why or if it has to be without looking at all of your code) and therefore you cannot call non-static methods from within it, such as uiLoadDevices
I would advise taking a look at your code and update your uiLoadStatus to not be static if at all possible. Abusing static can lead to sloppy code.

Related

TCP socket in Android

My problem is I have implemented a TCP socket client in android which sends continuously "Hello" messages to the server to maintain a client-server connection and receives messages from the server.
In Android, I have initialized a boolean variable that is controlling the thread if my app is in the background I make the "AppConfig.finished" variable true inactivity on pause and on stop method to stop the socket thread and make it false when in on resume state.
But my app is consuming high CPU usage which is making my app slow, I have checked it in android's profiler. Please help me to optimize it.
The code is given below.
public class MyTcp extends Thread{
private BufferedInputStream inputStream;
private BufferedOutputStream outputStream;
private Socket MySock;
private static SocketStatus SS;
private int ConnectAttemptCount = 0;
private CheckConnectionStatus CheckStatus = null;
public boolean FirstAttempt = true;
public boolean Continue = true;
private boolean isDirectChecked = false;
String tempData = "";
private final ArrayBlockingQueue<String> Queue = new ArrayBlockingQueue<>(100);
public MyTcp(SocketStatus SS) {
MyTcp.SS = SS;
MyTcp.SS.isConnected = false;
setDaemon(true);
Thread t = new Thread(new DequeueMessageThread());
t.setName(SS.SocketName + " DequeqeMessageThread");
t.start();
setName(SS.SocketName);
}
public void Dispose() {
try {
Continue = false;
SS.isConnected = false;
if(inputStream != null) {
inputStream.close();
}
if(outputStream !=null) {
outputStream.close();
}
if(MySock != null) {
MySock.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
if(!Logs.isFinished) {
try {
while (Continue) {
if (SS.isConnected) {
String fromServer = ReceiveMsg();
if (fromServer.compareTo("") != 0) {
Queue.put(fromServer);
}
ConnectAttemptCount = 0;
} else {
if (ConnectAttemptCount < SS.ConnectAttempt) {
println("run>>" + "Connection Attempt" + ConnectAttemptCount);
ConnectAttemptCount++;
Connect();
} else {
println("run>>" + "Unable To Connect to server");
break;
}
}
}
} catch (Exception e) {
println("run Exception>>" + e);
}
}
}
public void Connect() {
if(!Logs.isFinished) {
try {
if (SS.isDoQueueEmptyOnConnect) {
Queue.clear();
tempData = "";
}
if (FirstAttempt) {
FirstAttempt = false;
} else {
Utilities.println("Trying to connect with " + SS.ServerIP + " on Port " + SS.Port);
_fireStatsEvent(Status.Reconnecting, "Trying to connect with " + SS.ServerIP);
Random generator = new Random();
long wait = (long) generator.nextInt(3000) + 500;
Thread.sleep(wait);
}
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
return (new Socket(SS.ServerIP, SS.Port));
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SS.isConnected = true;
SocketStatus.MySock = MySock;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + SS.ServerIP + " on Port " + SS.Port);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (Exception e) {
println("Connect>>" + e);
}
int ConnectToIPCount = 0;
if (!SS.isConnected) {
while (!SS.isConnected && ConnectToIPCount < SS.ServerIPList.size()) {
final String IP_ = SS.ServerIPList.get(ConnectToIPCount).toString();
final int Port_ = SS.Port;
println("Connect>>" + "Trying to connect with " + IP_ + " on Port " + Port_);
ConnectToIPCount++;
try {
Thread.sleep(5000);
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
if (!isDirectChecked) {
isDirectChecked = true;
Socket tempSock = new Socket(Proxy.NO_PROXY);
tempSock.connect(new InetSocketAddress(IP_, Port_));
return tempSock;
} else {
return (new Socket(IP_, Port_));
}
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SocketStatus.MySock = MySock;
SS.isConnected = true;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + IP_ + " on port " + Port_);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (UnknownHostException e) {
println("Connect UnknownHostException>>" + e.toString());
} catch (IOException e) {
println("Connect IOException>>" + e.toString());
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
}
}
}
}
public void SendMsg(String sendMsg) {
if(!Logs.isFinished) {
try {
println("SendMsg>>" + sendMsg);
if (MySock != null && MySock.isConnected()) {
try {
byte[] b = null;
b = sendMsg.getBytes();
outputStream.write(b, 0, b.length);
outputStream.flush();
} catch (SocketException | SocketTimeoutException e) {
if (MySock != null) {
MySock.close();
}
SS.isConnected = false;
} catch (Exception e) {
println("SendMsg Exception>>" + e.toString());
}
}
} catch (Exception e) {
Log.d("TCP Client SendMsg >>", "Unable To Connect to server");
}
}
}
public String ReceiveMsg() {
String recvMsg = "";
if(!Logs.isFinished) {
try {
byte[] b = new byte[8092 * 6];
int recvsz = 0;
if (MySock != null && MySock.isConnected()) {
recvsz = inputStream.read(b, 0, b.length);
if (recvsz > 0) {
try {
byte[] b2 = new byte[recvsz];
System.arraycopy(b, 0, b2, 0, b2.length);
recvMsg = (new String(b2));
if (recvMsg.length() > 0) {
SS.LastMsgTime = new Date();
}
} catch (Exception e) {
println("ReceiveMsg Exception>>" + e.toString());
}
}
}
} catch (Exception e) {
if (SS.isConnected) {
Utilities.handleException(e);
}
SS.isConnected = false;
println("ReceiveMsg Exception>>>" + e.toString());
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + e.toString() + "'");
}
}
return recvMsg;
}
public void println(String msg) {
if (SS.Debug) {
String strDateFormat1 = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(strDateFormat1);
Utilities.println(SS.SocketName + " (" + sdf1.format(new Date()) + ") " + msg);
}
}
private final List<MessageRecieveListner> _listeners = new ArrayList<>();
private final List<MessageRecieveListner> _listenersStrength = new ArrayList<>();
public synchronized void addListener(MessageRecieveListner l) {
_listeners.add(l);
_listenersStrength.add(l);
}
private synchronized void _fireMessageEvent(String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, msg);
for (MessageRecieveListner listener : _listeners) {
listener.MessageRecieved(MsgEvent);
}
}
public synchronized void _fireStatsEvent(Status status, String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, status, msg);
for (MessageRecieveListner listener : _listeners) {
listener.ConnectionStatus(MsgEvent);
}
}
private class DequeueMessageThread implements Runnable {
public DequeueMessageThread() {
}
#Override
public void run() {
if(!Logs.isFinished) {
while (Continue) {
if (!Queue.isEmpty()) {
try {
String data = Queue.take().trim();
if (SS.MessageParser.length() > 0) {
if (data.lastIndexOf(SS.MessageParser) == data.length() - 1) {
_fireMessageEvent(tempData + data);
tempData = "";
} else {
if (data.indexOf(SS.MessageParser) > 0) {
String particalCompleteData = tempData + data.substring(0, data.lastIndexOf(SS.MessageParser));
tempData = data.substring(data.lastIndexOf(SS.MessageParser) + 1);
_fireMessageEvent(particalCompleteData);
Utilities.println("incomplete data");
}
}
} else {
_fireMessageEvent(data);
}
} catch (Exception ex) {
ex.printStackTrace();
Continue = false;
}
}
}
}
}
}

How to transmit of stream of data to multiple devices using sockets in Android?

I am trying to transmit a continuous stream of data to multiple devices over a portable hotspot connection using sockets.
I am facing two problems:
The message only gets displayed to the client AFTER all the messages are displayed in msg TextView on the server end. So if I use an infinite while(true) loop instead of for(int i = 0; i < 1000; i++), in ServerSocketReplyThread, the message never gets transmitted, and the client eventually crashes
I am unable to connect another client to the server until all the messages have been transmitted to the first client.
How do I structure the code to ensure simultaneous, real-time transmission to multiple clients?
Here's what the code looks like:
I am using an activity called Transmit activity, where I am instantiating the msg Textview, which replays the sent messages, and a server object.
msg = (TextView) findViewById(R.id.server_replayed_messages);
Server server = new Server(this);
The Server class is as follows:
public class Server {
TransmitActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ArrayList<Socket> socketList = new ArrayList<Socket>();
public Server(TransmitActivity a) {
this.activity = a;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread =
new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
for(int i = 0; i < 1000; i++) {
String msgReply = DateFormat.getDateTimeInstance().format(new Date());
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.flush();
message += "replayed: " + msgReply + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong in SocketServerReplyThread! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
}
}
}
}
On the client side I have a ReceiveActivity, where I am using the following code when a "Connect" button is clicked:
Client myClient = new Client(editTextAddress.getText()
.toString(), Integer.parseInt(editTextPort
.getText().toString()), response);
myClient.execute();
The Client class is as follows:
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* 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);
}
}
Any help would be much appreciated.

Android "Only the original thread that created a view hierarchy can touch its views." error in Fragment [duplicate]

This question already has answers here:
Android "Only the original thread that created a view hierarchy can touch its views."
(33 answers)
Closed 5 years ago.
I've got this simple timer in my app which is runs in every 3 seconds.
It works perfectly if it's not in a fragment class.
But here in fragment I always got the error: Only the original thread that created a view hierarchy can touch its views.
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
String timeStamp = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss").format(Calendar
.getInstance().getTime());
System.out.println("TimeStamp: " + timeStamp);
// Read And Write Register Sample
port = Integer.parseInt(gConstants.port);
String refe = "0";// HEX Address
ref = Integer.parseInt(refe, 16);// Hex to int
count = 10; // the number Address to read
SlaveAddr = 1;
astr = gConstants.ip; // Modbus Device
InetAddress addr;
try {
addr = InetAddress.getByName(astr);
con = new TCPMasterConnection(addr); // the
// connection
} catch (UnknownHostException e2) {
e2.printStackTrace();
}
// 1.Prepare the request
/************************************/
Rreq = new ReadMultipleRegistersRequest(ref, count);
Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); // set Slave Address
Rres.setUnitID(SlaveAddr); // set Slave Address
// 2. Open the connection
con.setPort(port);
try {
con.connect();
System.out.println("Kapcsolódva!");
} catch (Exception e1) {
e1.printStackTrace();
}
con.setTimeout(2500);
// 3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
try {
trans.execute();
} catch (ModbusIOException e) {
e.printStackTrace();
} catch (ModbusSlaveException e) {
e.printStackTrace();
} catch (ModbusException e) {
e.printStackTrace();
}
/* Print Response */
Rres = (ReadMultipleRegistersResponse) trans
.getResponse();
System.out.println("Connected to= " + astr
+ con.isConnected() + " / Start Register "
+ Integer.toHexString(ref));
count = 10;
for (int k = 0; k < count; k++) {
System.out.println("The value READ: "
+ Rres.getRegisterValue(k) + " "
+ Rres.getUnitID());
ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";
// Adatbázisba írás
ContentValues modbusData = new ContentValues();
modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
// +
// érték
modbusData.put("timeStamp", timeStamp);
try {
gConstants.db.beginTransaction();
gConstants.db
.insert("Modbus", null, modbusData);
gConstants.db.setTransactionSuccessful();
} finally {
gConstants.db.endTransaction();
}
}
kiir.setText(ki_adat);
ki_adat = "";
}//run vége
}, 0, 3000);
This error occurs when trying to access UI elements from any thread that is not the UI thread.
To access/modify elements from a non-UI-thread, use runOnUIThread.
However as you need to change a UI element from within a fragment, runOnUIThread should be invoked onto the fragments owning activity. You can do this through getActivity().runOnUIThread().
EG:
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
myTextBox.setText("my text");
}
});
}
}, 0, 3000); // End of your timer code.
For further information see the following documentation:
Android Fragments (specifically, getActivity()).
TimerTask.
Invoking a Runnable on the UI thread.
you need to use the runOnUIThread() function I have an example somwhere that I will post when I find it.
you need to give your timer an instance of MainActivity alternatively see this question I asked Android image timing issues with what sounds like a similar thing to what you were trying to do
public static void updateText(Activity act, resID)
{
loadingText = (TextView) activity.findViewById(R.id.loadingScreenTextView);
act.runOnUiThread(new Runnable()
{
public void run()
{
loadingText.setText(resID);
}
});
}
You are doing UI operation from another thread. I suggest you to use following.
runOnUiThread(new Runnable() {
#Override
public void run() {
kiir.setText(ki_adat);
}
2 solutions :
Use the View.post(Runnable) method
Use the Activity.post(Runnable) method
And put the myTextView.setText(str) call in the run() method of the Runnable object.
Try this:
textView.post(new Runnable() {
#Override
public void run() {
textView.setText("Hello!"); }
});
TRY THIS: put this part of code somewhere but not in activity onCreate method
public void LoadTable(final String u, final String k)
{
// runOnUiThread need to be used or error will appear
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
//method which was problematic and was casing a problem
createTable(u, k);
}
});
} catch (Exception exception) {
createAndShowDialog(exception, "Error");
}
return null;
}
}.execute();
}
Try this
new CountDownTimer(365*24*60*60, 3000) {
public void onTick(long millisUntilFinished) {
String timeStamp = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss").format(Calendar
.getInstance().getTime());
System.out.println("TimeStamp: " + timeStamp);
// Read And Write Register Sample
port = Integer.parseInt(gConstants.port);
String refe = "0";// HEX Address
ref = Integer.parseInt(refe, 16);// Hex to int
count = 10; // the number Address to read
SlaveAddr = 1;
astr = gConstants.ip; // Modbus Device
InetAddress addr;
try {
addr = InetAddress.getByName(astr);
con = new TCPMasterConnection(addr); // the
// connection
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// 1.Prepare the request
/************************************/
Rreq = new ReadMultipleRegistersRequest(ref, count);
Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); // set Slave Address
Rres.setUnitID(SlaveAddr); // set Slave Address
// 2. Open the connection
con.setPort(port);
try {
con.connect();
System.out.println("Kapcsolódva!");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
con.setTimeout(2500);
// 3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
try {
trans.execute();
} catch (ModbusIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ModbusSlaveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ModbusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Print Response */
Rres = (ReadMultipleRegistersResponse) trans
.getResponse();
System.out.println("Connected to= " + astr
+ con.isConnected() + " / Start Register "
+ Integer.toHexString(ref));
count = 10;
for (int k = 0; k < count; k++) {
System.out.println("The value READ: "
+ Rres.getRegisterValue(k) + " "
+ Rres.getUnitID());
ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";
// Adatbázisba írás
ContentValues modbusData = new ContentValues();
modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
// +
// érték
modbusData.put("timeStamp", timeStamp);
try {
gConstants.db.beginTransaction();
gConstants.db
.insert("Modbus", null, modbusData);
gConstants.db.setTransactionSuccessful();
} finally {
gConstants.db.endTransaction();
}
}
kiir.setText(ki_adat);
ki_adat = "";
}
public void onFinish() {}
}.start();

Android Audio Track Play with noise

I am working on a peer to peer to voice call application in Android for my college project. I found sample code for streaming the mic audio through UDP. That code will help me to stream the WAV file through UDP. But it doesn't play some files properly. And also that code doesn't stream mic audio.
Please help me.
public class UdpStream extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.udpstream);
Button btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "btnSend clicked");
SendAudio();
}
});
Button btnRecv = (Button)findViewById(R.id.btnRecv);
btnRecv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "btnRecv clicked");
RecvAudio();
}
});
Button btnStrmic = (Button)findViewById(R.id.btnStrmic);
btnStrmic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "btnStrmic clicked");
SendMicAudio();
}
});
}
static final String LOG_TAG = "UdpStream";
static final String AUDIO_FILE_PATH = "/sdcard/1.wav";
static final int AUDIO_PORT = 2048;
static final int SAMPLE_RATE = 8000;
static final int SAMPLE_INTERVAL = 20; // milliseconds
static final int SAMPLE_SIZE = 2; // bytes per sample
static final int BUF_SIZE = SAMPLE_INTERVAL*SAMPLE_INTERVAL*SAMPLE_SIZE*2;
protected String host="localhost";
public void RecvAudio()
{
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start recv thread, thread id: "
+ Thread.currentThread().getId());
AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC,
SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, BUF_SIZE,
AudioTrack.MODE_STREAM);
track.play();
try
{
DatagramSocket sock = new DatagramSocket(AUDIO_PORT);
byte[] buf = new byte[BUF_SIZE];
while(true)
{
DatagramPacket pack = new DatagramPacket(buf, BUF_SIZE);
sock.receive(pack);
Log.d(LOG_TAG, "recv pack: " + pack.getLength());
track.write(pack.getData(), 0, pack.getLength());
}
}
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException: " + se.toString());
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException" + ie.toString());
}
} // end run
});
thrd.start();
}
Toast toast;
int port=3008;
public void SendAudio()
{
toast=Toast.makeText(getApplicationContext(), port + " : " + host , Toast.LENGTH_SHORT);
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start send thread, thread id: "
+ Thread.currentThread().getId());
long file_size = 0;
int bytes_read = 0;
int bytes_count = 0;
File audio = new File(AUDIO_FILE_PATH);
FileInputStream audio_stream = null;
file_size = audio.length();
byte[] buf = new byte[BUF_SIZE];
try
{
EditText d= (EditText) findViewById(R.id.txttohost);
host=d.getText().toString();
if(host=="")
{
port=2048;
host="localhost";
}
port=2048;
InetAddress addr = InetAddress.getByName(host);
toast.setText(port + " : " + addr.toString());
toast.show();
DatagramSocket sock = new DatagramSocket();
audio_stream = new FileInputStream(audio);
while(bytes_count < file_size)
{
bytes_read = audio_stream.read(buf, 0, BUF_SIZE);
DatagramPacket pack = new DatagramPacket(buf, bytes_read,
addr, port);
sock.send(pack);
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
}
}
catch (InterruptedException ie)
{
Log.e(LOG_TAG, "InterruptedException");
}
catch (FileNotFoundException fnfe)
{
Log.e(LOG_TAG, "FileNotFoundException");
}
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException");
}
catch (UnknownHostException uhe)
{
Log.e(LOG_TAG, "UnknownHostException");
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException");
}
} // end run
});
thrd.start();
}
public void SendMicAudio()
{
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start SendMicAudio thread, thread id: "
+ Thread.currentThread().getId());
AudioRecord audio_recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SAMPLE_RATE,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT) * 10);
int bytes_read = 0;
int bytes_count = 0;
byte[] buf = new byte[BUF_SIZE];
try
{
InetAddress addr = InetAddress.getLocalHost();
DatagramSocket sock = new DatagramSocket();
while(true)
{
bytes_read = audio_recorder.read(buf, 0, BUF_SIZE);
DatagramPacket pack = new DatagramPacket(buf, bytes_read,
addr, AUDIO_PORT);
sock.send(pack);
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
}
}
catch (InterruptedException ie)
{
Log.e(LOG_TAG, "InterruptedException");
}
// catch (FileNotFoundException fnfe)
// {
// Log.e(LOG_TAG, "FileNotFoundException");
// }
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException");
}
catch (UnknownHostException uhe)
{
Log.e(LOG_TAG, "UnknownHostException");
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException");
}
} // end run
});
thrd.start();
}
}
As for as concern with my question....
The Solution is Always while playing the Audio through out speaker will cause Some noise....
So i found the following two solution to fix that...
1) Play the audio through ear piece
audio_service.setSpeakerphoneOn(false);
audio_service.setMode(AudioManager.MODE_IN_CALL);
audio_service.setRouting(AudioManager.MODE_NORMAL,AudioManager.ROUTE_EARPIECE,
AudioManager.ROUTE_ALL);
2) Next way to do use Some Audio Codec for encoding and Decoding Your Audio to play that in noiseless..

Stop httpConnection blackberry after time

i have a problem. I want to stop an httpconnection after x seconds, how can i do that? I thought something like a timertask that executes a httpconnection.close() after x seconds or something like that. Here is my code where i use my connection.
public void run() {
boolean hasCoverage = (RadioInfo.getState() == RadioInfo.STATE_ON)
&& (RadioInfo.getSignalLevel() != RadioInfo.LEVEL_NO_COVERAGE);
if (hasCoverage) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
popup = new MyPopup("Cargando Incidentes...");
UiApplication.getUiApplication().pushModalScreen(popup);
}
});
try {
HttpConnection conn = null;
String URL = "anypage.php";
conn = (HttpConnection) Connector.open(URL);
InputStream contentIn = conn.openInputStream();
byte[] data = new byte[400];
int length = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (length = contentIn.read(data))) {
raw.append(new String(data, 0, length));
str = raw.toString();
}
} catch (Exception e) {
e.printStackTrace();
mainScreen.add(new RichTextField(
"Error ThreadIncidentesConnection: " + e.toString()));
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
String datos[] = mainScreen.split(str, "ENDOFPAGE");
// mainScreen.add(new RichTextField(""+datos[0]));
datos[0] = datos[0].substring(2, datos[0].length());
mainScreen.vecRegistro = mainScreen
.split(datos[0], "$");
mainScreen.insertoEnBd();
mainScreen.insertoEnTablaDatosBD(_act);
UiApplication.getUiApplication().popScreen(popup);
} catch (Exception e) {
e.printStackTrace();
mainScreen.add(new RichTextField(
"Error ThreadIncidentes.run: " + e.toString()));
}
}
});
} else {
mainScreen.add(new RichTextField("No hay conexión disponible."));
}
}

Categories

Resources