[英]How to run specific methods infinite time in background per 5 seconds in 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.