I have a client in android connected to a server in c++ using TCP sockets. I need my app to constantly send an image to the server. I tried using an infinite(while) loop, but then my app does not do anything else while running the loop, and I need my app to constantly send the image but also be able to run tasks at the same time. this is my code:
class sendImage implements Runnable{
@Override
public void run() {
while(true){
try {
Bitmap bmp=screenShot();
ByteArrayOutputStream bosBitmap = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 50, bosBitmap);
byte[] arrayBitmap = bosBitmap.toByteArray();
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos = new DataOutputStream(os);
dos.write(arrayBitmap, 0, arrayBitmap.length);
dos.flush();
memecontentView.destroyDrawingCache();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and when I click a button this is how I initialize the thread
public void onClick(View view) {
new Thread(new sendImage()).start();
}
But when I click the button, the image is sent but it does not allow me to do anything else, if I press another button, my app closes How can I run an infinite loop that allows my app to perform other tasks at the same time?
如果您需要长时间保持线程运行,强烈建议您使用java.util.concurrent包提供的各种API,例如Executor,ThreadPoolExecutor和FutureTask。
I post my solution if somebody finds it helpful I just implemented an AsyncTask, it works great:
public class SendImage extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... arg0){
while(true){
try {
Bitmap bmp=screenShot();
ByteArrayOutputStream bosBitmap = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 30, bosBitmap);
byte[] arrayBitmap = bosBitmap.toByteArray();
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos = new DataOutputStream(os);
dos.write(arrayBitmap, 0, arrayBitmap.length);
dos.flush();
memecontentView.destroyDrawingCache();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.