繁体   English   中英

如何在后台android中运行无限循环

[英]how to run infinite loop in background android

我有一个Android中的客户端使用TCP套接字连接到C ++中的服务器。 我需要我的应用程序不断将图像发送到服务器。 我尝试使用无限(while)循环,但是我的应用程序在运行循环时不执行任何其他操作,因此我需要我的应用程序不断发送图像,但还能够同时运行任务。 这是我的代码:

    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();
            }
        }       
    }
}

当我单击按钮时,这就是初始化线程的方式

public void onClick(View view) {
    new Thread(new sendImage()).start();
}

但是,当我单击按钮时,将发送图像,但不允许我执行其他任何操作,如果按下另一个按钮,则我的应用程序将关闭。如何运行无限循环,使我的应用程序可以同时执行其他任务?

如果您需要长时间保持线程运行,强烈建议您使用java.util.concurrent包提供的各种API,例如Executor,ThreadPoolExecutor和FutureTask。

如果有人发现它对我有帮助,那么我发布了我的解决方案,我刚刚实现了AsyncTask,它很好用:

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();
            }
        }       
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM