机器人如何运行的AsyncTask每一秒? [英] Android How to run an AsyncTask every second?

查看:117
本文介绍了机器人如何运行的AsyncTask每一秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的Andr​​oid和没有真正知道如何处理这个问题:我有一个AsyncTask的读取从一个XML文件中的位置(X,Y,Z)。由于这个位置发生变化的每一秒,我想,当我按下一个按钮(被称为具有StartListener)来读取并绘制每一个新的位置,连续停止阅读它,当我再次preSS按钮...
有人能帮帮我吗? - 这是我MainActivity的一部分

(就目前我的应用程序读取,只有绘制的位置,当我preSS按钮...)

 私人OnClickListener StartListener =新OnClickListener(){

          @覆盖
          公共无效的onClick(视图v){

                TextView的ButText =(TextView中)findViewById(R.id.buttonStart);

                 字符串值= ButText.getText()的toString()。
                 如果(value.equals(开始定位)){
                     ButText.setText(停止定位);

                     新PositionAsync()执行()。 //读取XML文件中的数据

                 }
                 否则,如果(value.equals(停止定位)){
                     ButText.setText(开始定位);
                     //新PositionAsync()取消(真);
                 }
            }
      }; // END LISTENER启动按钮


//读取XML文件
类PositionAsync扩展的AsyncTask<虚空,虚空,虚空> {

    XMLHelper帮手;
    @覆盖
    保护无效doInBackground(虚空......为arg0){
        辅助=新XMLHelper();
        helper.get();
        返回null;
    }

    @覆盖
    保护无效onPostExecute(无效的结果){

        油漆paintBlack =新的油漆(); paintBlack.setAntiAlias​​(真正的); paintBlack.setColor(Color.BLACK);

        BitmapFactory.Options myOptions =新BitmapFactory.Options();
        myOptions.inDither = TRUE;
        myOptions.inScaled = FALSE;
        myOptions.in preferredConfig = Bitmap.Config.ARGB_8888; //重要
        myOptions.inPurgeable = TRUE;
        文件的ImageSource =新的文件(/ SD卡/ app_background3.jpg);
        位图bitmap2 = BitmapFactory.de codeFILE(ImageSource.getAbsolutePath(),myOptions);
        位图workingBitmap = Bitmap.createBitmap(bitmap2);
        位图mut​​ableBitmap2 = workingBitmap.copy(Bitmap.Config.ARGB_8888,真正的);

        帆布canvas2 =新的Canvas(mutableBitmap2);

        浮RoomWidthPx = canvas2.getWidth();
        浮RoomHeightPx = canvas2.getHeight();
        浮动RoomXmeter =(浮点)9.3;
        浮动RoomZmeter =(浮点)14.7;

        对于(PositionValue位置:helper.positions){

            串POSX = position.getPositionX();字符串波西= position.getPositionY();串PosZ = position.getPositionZ();

            浮动X = Float.valueOf(POSX);浮动Y = Float.valueOf(波西);浮Z = Float.valueOf(PosZ);

            浮XM = X * RoomWidthPx / RoomXmeter;
            浮ZM = Z * RoomHeightPx / RoomZmeter;

            canvas2.drawCircle(XM,ZM,25,paintBlack);

            ImageView的ImageView的=(ImageView的)findViewById(R.id.imageView1);
            imageView.setAdjustViewBounds(真正的);
            imageView.setImageBitmap(mutableBitmap2);

            //保存图纸变成文件
            FileOutputStream中FOS = NULL;
            尝试 {
            FOS =新的FileOutputStream(/sdcard/app_background3.jpg);
            mutableBitmap2.com preSS(Bitmap.Com pressFormat.JPEG,95,FOS);
            }赶上(的Throwable前){ex.printStackTrace(); }
        };

    }
} // END读取XML文件
 

解决方案

我认为你正在做太多的任务,在短短的一秒钟。你可以,而是prepare所有重型员工在在preExecute()中的AsyncTask中,读取XML并执行绘画中的 doInBackground(),resfresh中的ImageView的 onProgressUpdate()最后,当任务完成后,将图像保存到 SD卡

我已经修改了的AsyncTask 来实现上面的场景,我还没有测试它,但它给你的想法。

在您的活动的的onCreate()方法启动AsyncTask的一次。它保持执行或睡觉,直到你设置Quit_Task变量设置为true。当按钮为pressed您切换变量 Do_Drawing:Do_Drawing = Do_Drawing; ,就是这样

 私人布尔Do_Drawing = FALSE;
私人布尔Quit_Task = FALSE;

//读取XML文件
类PositionAsync扩展的AsyncTask<虚空,虚空,虚空>
{
    涂料paintBlack;
    BitmapFactory.Options myOptions;
    位图mut​​ableBitmap2;
    帆布canvas2;
    XMLHelper帮手;

    无效睡眠(INT MS)
    {
        尝试
        {
            视频下载(毫秒);
        }
        赶上(例外五)
        {
        }
    }

    @覆盖
    在preExecute保护无效()
    {
        // prepare家居doInBackground线
        paintBlack =新的油漆();
        paintBlack.setAntiAlias​​(真正的);
        paintBlack.setColor(Color.BLACK);
        myOptions =新BitmapFactory.Options();
        myOptions.inDither = TRUE;
        myOptions.inScaled = FALSE;
        myOptions.in preferredConfig = Bitmap.Config.ARGB_8888; //重要
        myOptions.inPurgeable = TRUE;
        文件的ImageSource =新的文件(/ SD卡/ app_background3.jpg);
        位图bitmap2 = BitmapFactory.de codeFILE(ImageSource.getAbsolutePath(),myOptions);
        位图workingBitmap = Bitmap.createBitmap(bitmap2);
        mutableBitmap2 = workingBitmap.copy(Bitmap.Config.ARGB_8888,真正的);
        canvas2 =新的Canvas(mutableBitmap2);
        辅助=新XMLHelper();
    }

    @覆盖
    保护无效doInBackground(空...为arg0)
    {
        而(!Quit_Task)
        {
            //睡到按钮是pressed或退出
            而(!Do_Drawing)
            {
                睡眠(1000);
                如果(Quit_Task)
                    返回null;
            }

            浮RoomWidthPx = canvas2.getWidth();
            浮RoomHeightPx = canvas2.getHeight();
            浮动RoomXmeter =(浮点)9.3;
            浮动RoomZmeter =(浮点)14.7;
            //继续绘制直到按钮pssed $ P $又或退出
            而(Do_Drawing)
            {
                如果(Quit_Task)
                    返回null;
                helper.get();
                对于(PositionValue位置:helper.positions)
                {
                    串POSX = position.getPositionX();
                    字符串波西= position.getPositionY();
                    串PosZ = position.getPositionZ();

                    浮动X = Float.valueOf(POSX);
                    浮动Y = Float.valueOf(波西);
                    浮Z = Float.valueOf(PosZ);

                    浮XM = X * RoomWidthPx / RoomXmeter;
                    浮ZM = Z * RoomHeightPx / RoomZmeter;

                    canvas2.drawCircle(XM,ZM,25,paintBlack);
                }
                this.publishProgress((无效)NULL);
                睡眠(1000);
            }
        }
        返回null;
    }

    @覆盖
    保护无效onProgressUpdate(空...进度)
    {
        //一旦所有的点读及放大器;绘制刷新ImageView的
        尝试
        {
            ImageView的ImageView的=(ImageView的)findViewById(R.id.imageView1);
            imageView.setAdjustViewBounds(真正的);
            imageView.setImageBitmap(mutableBitmap2);
        }
        赶上(例外五)
        {
            e.printStackTrace();
        }
    }

    @覆盖
    保护无效onPostExecute(虚空结果)
    {
        //保存图纸变成文件,一旦任务完成。
        FileOutputStream中FOS = NULL;
        尝试
        {
            FOS =新的FileOutputStream(Environment.getExternalStorageDirectory()getPath()+app_background3.jpg。);
            mutableBitmap2.com preSS(Bitmap.Com pressFormat.JPEG,95,FOS);
        }
        捕获(的Throwable前)
        {
            ex.printStackTrace();
        }
    }
} // END读取XML文件
 

I'm new in Android and not really knowing how to deal this problem: I have an AsyncTask which reads a position (X,Y,Z) from a XML file. As this position changes every second, I want, after I push a button (called with "StartListener") to read and draw every new position CONTINUOUSLY and stop reading it when I press the button again...
Somebody can help me? - Here is a part of my MainActivity

(For the moment my app reads and draws a position only when I press the button...)

      private OnClickListener StartListener = new OnClickListener() {

          @Override
          public void onClick(View v) {

                TextView ButText = (TextView)findViewById(R.id.buttonStart);

                 String value=ButText.getText().toString();
                 if(value.equals("Start positioning")){
                     ButText.setText("Stop positioning");

                     new PositionAsync().execute(); //read data from XML file

                 }
                 else if(value.equals("Stop positioning")){
                     ButText.setText("Start positioning");
                     //new PositionAsync().cancel(true);
                 }              
            }                   
      }; // END LISTENER START BUTTON


// READ XML FILE
class PositionAsync extends AsyncTask<Void, Void, Void> {

    XMLHelper helper;
    @Override
    protected Void doInBackground(Void... arg0) {
        helper = new XMLHelper();
        helper.get();
        return null;
    }   

    @Override
    protected void onPostExecute(Void result) {         

        Paint paintBlack = new Paint(); paintBlack.setAntiAlias(true); paintBlack.setColor(Color.BLACK);

        BitmapFactory.Options myOptions = new BitmapFactory.Options();
        myOptions.inDither = true;
        myOptions.inScaled = false;
        myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
        myOptions.inPurgeable = true;
        File ImageSource = new File("/sdcard/app_background3.jpg");
        Bitmap bitmap2 = BitmapFactory.decodeFile(ImageSource.getAbsolutePath(),myOptions);         
        Bitmap workingBitmap = Bitmap.createBitmap(bitmap2);
        Bitmap mutableBitmap2 = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);

        Canvas canvas2 = new Canvas(mutableBitmap2);

        float RoomWidthPx = canvas2.getWidth();
        float RoomHeightPx = canvas2.getHeight();
        float RoomXmeter = (float) 9.3;
        float RoomZmeter = (float) 14.7;

        for (PositionValue position : helper.positions) {

            String PosX = position.getPositionX(); String PosY = position.getPositionY(); String PosZ = position.getPositionZ();

            float x = Float.valueOf(PosX); float y = Float.valueOf(PosY); float z = Float.valueOf(PosZ);

            float xm = x*RoomWidthPx/RoomXmeter; 
            float zm = z*RoomHeightPx/RoomZmeter;

            canvas2.drawCircle(xm, zm, 25, paintBlack);

            ImageView imageView = (ImageView)findViewById(R.id.imageView1);
            imageView.setAdjustViewBounds(true);
            imageView.setImageBitmap(mutableBitmap2);

            // SAVE DRAWINGS INTO FILE
            FileOutputStream fos = null;
            try {
            fos = new FileOutputStream ("/sdcard/app_background3.jpg");
            mutableBitmap2.compress (Bitmap.CompressFormat.JPEG, 95, fos); 
            } catch (Throwable ex) {ex.printStackTrace (); }    
        };

    }
} //END READ XML FILE

解决方案

I think you are doing too many task in just one second. You could, instead, prepare all heavy staff in the onPreExecute() of the AsyncTask, read the XML and do the painting in the doInBackground(), resfresh the ImageView in the onProgressUpdate() and finally, when the task is done, save the image to the sdcard.

I've modified your Asynctask to accomplish the above scenario, I've not tested it but it gives you the idea.

In the onCreate() method of your activity you start the AsyncTask just once. It stays executing or sleeping until you set the Quit_Task variable to true. When the button is pressed you toggle the variable Do_Drawing: Do_Drawing=!Do_Drawing; and that's it.

private boolean Do_Drawing = false;
private boolean Quit_Task = false;

// READ XML FILE
class PositionAsync extends AsyncTask<Void, Void, Void>
{
    Paint paintBlack;
    BitmapFactory.Options myOptions;
    Bitmap mutableBitmap2;
    Canvas canvas2;
    XMLHelper helper;

    void Sleep(int ms)
    {
        try
        {
            Thread.sleep(ms);
        }
        catch (Exception e)
        {
        }
    }

    @Override
    protected void onPreExecute()
    {
        // Prepare everything for doInBackground thread
        paintBlack = new Paint();
        paintBlack.setAntiAlias(true);
        paintBlack.setColor(Color.BLACK);
        myOptions = new BitmapFactory.Options();
        myOptions.inDither = true;
        myOptions.inScaled = false;
        myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
        myOptions.inPurgeable = true;
        File ImageSource = new File("/sdcard/app_background3.jpg");
        Bitmap bitmap2 = BitmapFactory.decodeFile(ImageSource.getAbsolutePath(), myOptions);
        Bitmap workingBitmap = Bitmap.createBitmap(bitmap2);
        mutableBitmap2 = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
        canvas2 = new Canvas(mutableBitmap2);
        helper = new XMLHelper();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        while (!Quit_Task)
        {
            // Sleep until button is pressed or quit
            while (!Do_Drawing)
            {
                Sleep(1000);
                if (Quit_Task)
                    return null;
            }

            float RoomWidthPx = canvas2.getWidth();
            float RoomHeightPx = canvas2.getHeight();
            float RoomXmeter = (float) 9.3;
            float RoomZmeter = (float) 14.7;
            // keep drawing until button is pressed again or quit
            while (Do_Drawing)
            {
                if (Quit_Task)
                    return null;
                helper.get();
                for (PositionValue position : helper.positions)
                {
                    String PosX = position.getPositionX();
                    String PosY = position.getPositionY();
                    String PosZ = position.getPositionZ();

                    float x = Float.valueOf(PosX);
                    float y = Float.valueOf(PosY);
                    float z = Float.valueOf(PosZ);

                    float xm = x * RoomWidthPx / RoomXmeter;
                    float zm = z * RoomHeightPx / RoomZmeter;

                    canvas2.drawCircle(xm, zm, 25, paintBlack);
                }
                this.publishProgress((Void) null);
                Sleep(1000);
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... progress)
    {
        // once all points are read & drawn refresh the imageview
        try
        {
            ImageView imageView = (ImageView) findViewById(R.id.imageView1);
            imageView.setAdjustViewBounds(true);
            imageView.setImageBitmap(mutableBitmap2);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPostExecute(Void result)
    {
        // SAVE DRAWINGS INTO FILE once the task is done.
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "app_background3.jpg");
            mutableBitmap2.compress(Bitmap.CompressFormat.JPEG, 95, fos);
        }
        catch (Throwable ex)
        {
            ex.printStackTrace();
        }
    }
} // END READ XML FILE

这篇关于机器人如何运行的AsyncTask每一秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆