同时运行多个Asyntask

时间:2014-12-01 06:13:59

标签: java android

我在服务器端有服务器客户端通信程序我有摄像头和我的Android应用程序控制的摄像头作为客户端它正在工作,但问题是服务器内存已满,服务器正在停止摄像头并发送消息到客户端,如果客户端希望自己停止摄像头,则客户端向服务器发送命令,服务器停止摄像头。 问题是,如果我正在按摩"记忆力充足,那么我只能按摩按摩。然后我没有得到按摩"停止摄像机"当用户想要自己杀死并且如果我设法得到了#34;停止摄像机"消息然后我没有得到"内存全按摩"

这是我的代码请帮帮我 提前谢谢

/** here is the recording start button I am calling a asyntask for recording
       * Record  and store video at battery control unit(server end) at background
       */
        record=(ImageButton)findViewById(R.id.record);
        record.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if(socket==null){
                    Toast.makeText(getApplicationContext(), "connection not establised", Toast.LENGTH_SHORT).show();
                }
                else{
                    pDialog.show();
                    suspended=false;
                    start=false;
                    new CommunicationTaskrec().execute();
                }
            }
        });

/ **        *记录的异步任务,在背景上运行。        * /

     public class CommunicationTaskrec  extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {
                String str = "3";
                PrintWriter out = null;
                try {
                      out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream())),
                            true);
                }   catch (IOException e1) {
                    e1.printStackTrace();
                }
                out.println(str);
             String resultrec="testing the UI Thread update";
             BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }   catch (IOException e) {
                e.printStackTrace();
            }
            try {
                resultrec = in.readLine();
            }   catch (IOException e) {
                e.printStackTrace();
            }
            //Log.d("inside bg thread", resultrec);
            mHandler.obtainMessage(MESSAGE_READ, resultrec).sendToTarget();
            out.flush();
           // new Thread(new RecThread()).start();
           // new CommunicationTaskmemorycheck().execute();
            return resultrec; 
     }
    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
    }
   }

//这里是消息处理程序案例

           /** 
            * Creating a dialog box which shows a timer for the recording time
            */
                 case MESSAGE_READ:
                final String readBuf = (String) msg.obj;
                String string1 ="no enough space left on device";

                if(readBuf !=null){

                    if(readBuf.equalsIgnoreCase(string1))
                    {
                        pDialog.dismiss();
                        Toast.makeText(MainActivity.this, "NO Enough Space Left for Recording Please Remove some files at server end.", Toast.LENGTH_LONG).show();
                    }
                else{
                    pDialog.dismiss();
                    Toast.makeText(MainActivity.this, readBuf, Toast.LENGTH_LONG).show();

    //here is the dialog box where I have a stop button also by which user stopping the ///camera manually

                    View viewlist=MainActivity.this.getLayoutInflater().inflate(R.layout.timer, null);
                    dialog = new Dialog(MainActivity.this);
                    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                    dialog.setContentView(viewlist);
                    dialog.setTitle("Status.....");
                    dialog.setCancelable(false);
                    TextView text = (TextView) dialog.findViewById(R.id.valuerec);
                    text.setText("Want to stop the Recording ?");
                    TextView cur_val = (TextView) dialog.findViewById(R.id.curvaluerec);
                    cur_val.setText("Recording Duration..");
                    Button stop = (Button) dialog.findViewById(R.id.start);
                    mChronometer = (Chronometer) dialog.findViewById(R.id.chronometer);
                    mChronometer.start();
                    dialog.show();

                    //here a asyntask and it is used for getting the memory full message
                    //it run contentiously on background and when the memory is full it //recieve "memory full massage"

                       task = new AsyncTask<Void, Void, Void>() {
                         String result=null;
                        protected Void doInBackground(Void... params) {

                            Runnable action = new Runnable() {
                                public void run() {
                                    mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
                                }
                            };
                            try {

                                do {
                                    //Pause work if control is paused.
                                    //tControl.waitIfPaused();
                                    //Stop work if control is cancelled.
                                    if (tControl.isCancelled()) {
                                        suspended=true;
                                        break;
                                    }
                                    while(!suspended){
                                    String string1 ="memory full";
                                    BufferedReader in = null;
                                    try {
                                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        result = in.readLine();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    } 

                                    if((result!=null && result.equalsIgnoreCase(string1)) )
                                    {
                                        mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
                                        result=null;
                                        suspended=true;
                                        start=true;
                                        runOnUiThread(action);
                                        break;
                                        }
                                    }
                                }while (!suspended);
                            } catch (Exception e) {

                            }
                            return null;
                        }

                    };
                    task.execute();

//这里是对话框停止按钮,我有一个可运行的线程,当用户想要手动停止录制时,该线程用于向服务器发送//命令

                        stop.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            task.cancel(true);
                            tControl.cancel();
                            suspended=true;

                            dialog.dismiss();

                            dialog=null;
                            mChronometer.stop();

                            pDialog.show();

                            //this is the runnable thread where I am getting "stopping //camera "massage

                            new Thread(new Runnable() {
                                @SuppressLint("ShowToast")
                                public void run() {
                                     while (true) {
                                        String str = "8";
                                        PrintWriter out = null;
                                        try {
                                              out = new PrintWriter(new BufferedWriter(
                                                    new OutputStreamWriter(socket.getOutputStream())),
                                                    true);
                                        }   catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                     out.println(str);
                                     String resultcap=null;
                                     BufferedReader in = null;
                                    try {
                                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                    }   catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        resultcap = in.readLine();
                                    }   catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                        mHandler.obtainMessage(MESSAGE_READstoprunning, resultcap).sendToTarget();
                                        out.flush();
                                        //suspended=false;
                                        break;
                                    }
                                }
                            }
                            ).start();
                        }
                    });
                    }   
                }
                else{
                    pDialog.dismiss();
                    Toast.makeText(MainActivity.this, "error server not respondingrec", Toast.LENGTH_LONG).show();
                }
                break;

2 个答案:

答案 0 :(得分:3)

将execute()更改为executeOnExecutor(AsynTask.ThreadpoolExecutor)

答案 1 :(得分:1)

AsyncTasks doc

首次引入时,AsyncTasks在单个后台线程上串行执行。从DONUT开始,这被改为一个线程池,允许多个任务并行运行。从HONEYCOMB开始,任务在单个线程上执行,以避免由并行执行引起的常见应用程序错误。

如果您真的想要并行执行,可以调用 executeOnExecutor(java.util.concurrent.Executor, Object[])

使用THREAD_POOL_EXECUTOR。