0

I have create the Handler inside the activity onCreate method. This Hanlder is responsible to take screen shots after 10 seconds. Inside the run method I have used while(flag==true) and screen the capture util flag==false, But this stuck my activity. I can not able to work. And it take the screen shot over again and again of same image because of actvity is stuck. How I can work with my screen and what I am doing handler take the screen shot after 10 seconds? The while loop stuck my app.

It Take picture but I am not able to work with my activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    flag = true;


    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {

            while (flag == true) {
                String SCREENSHOTS_LOCATIONS = Environment
                        .getExternalStorageDirectory().toString() + "/re/";
                // Get root view
                View view = getWindow().getDecorView().getRootView();
                // Create the bitmap to use to draw the screenshot
                final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
                        view.getHeight(), Bitmap.Config.ARGB_8888);
                final Canvas canvas = new Canvas(bitmap);

                // Get current theme to know which background to use
                final Theme theme = getTheme();
                final TypedArray ta = theme
                        .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
                final int res = ta.getResourceId(0, 0);
                final Drawable background = getResources().getDrawable(res);

                // Draw background
                background.draw(canvas);

                // Draw views
                view.draw(canvas);
                FileOutputStream fos = null;

                try {
                    final File sddir = new File(SCREENSHOTS_LOCATIONS);
                    if (!sddir.exists()) {
                        sddir.mkdirs();
                    }

                    fos = new FileOutputStream(SCREENSHOTS_LOCATIONS + x
                            + ".jpg");
                    x++;
                    if (fos != null) {
                        if (!bitmap.compress(Bitmap.CompressFormat.JPEG,
                                90, fos)) {
                            Log.d("ScreenShot", "Compress/Write failed");
                        }
                        fos.flush();
                        fos.close();
                    }
                } catch (Exception e) {

                }
            }
        }

    }, 1000);

}
Sohaib Ahmed
  • 31
  • 1
  • 6
  • 1
    Can you post the code you've written ? – Ye Lin Aung Aug 25 '14 at 03:24
  • Possible duplicate of [Loop doesn't see changed value without a print statement](http://stackoverflow.com/questions/25425130/loop-doesnt-see-changed-value-without-a-print-statement) – jww Aug 25 '14 at 04:24
  • Try `handler.removeCallbacks(runnable);` after definind your runnable seperately. – Viswanath Lekshmanan Aug 25 '14 at 05:54
  • when I make separate runnable it give exception. IllegalArgumentException width and height > 0 "in createBitmap", Its mean its not take the view of current screen to get the height and width in separate ruunable – Sohaib Ahmed Aug 25 '14 at 08:36

1 Answers1

0

Maybe try using an AsyncTask or other thread. The postDelayed() function attaches to the main UI thread and locks up your app until run() is finished (which never happens because flag never equals false so the while loop becomes infinite?).

Here is an example using the ScheduledThreadPoolExecutor:

private ScheduledThreadPoolExecutor exec = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    flag = true;

    exec = new ScheduledThreadPoolExecutor(5);
    long interval = (long) 10; // 10 seconds for you
    exec.scheduleAtFixedRate(new savePicTask(), 0, interval, TimeUnit.SECONDS);

}

class savePicTask implements Runnable {
    @Override
    public void run() {
        while (flag == true) {
            String SCREENSHOTS_LOCATIONS = Environment
                    .getExternalStorageDirectory().toString() + "/re/";
            // Get root view
            View view = getWindow().getDecorView().getRootView();
            // Create the bitmap to use to draw the screenshot
            final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
                    view.getHeight(), Bitmap.Config.ARGB_8888);
            final Canvas canvas = new Canvas(bitmap);

            // Get current theme to know which background to use
            final Theme theme = getTheme();
            final TypedArray ta = theme
                    .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
            final int res = ta.getResourceId(0, 0);
            final Drawable background = getResources().getDrawable(res);

            // Draw background
            background.draw(canvas);

            // Draw views
            view.draw(canvas);
            FileOutputStream fos = null;

            try {
                final File sddir = new File(SCREENSHOTS_LOCATIONS);
                if (!sddir.exists()) {
                    sddir.mkdirs();
                }

                fos = new FileOutputStream(SCREENSHOTS_LOCATIONS + x
                        + ".jpg");
                x++;
                if (fos != null) {
                    if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
                        Log.d("ScreenShot", "Compress/Write failed");
                    }
                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {

            }
        }
    }       
}

EDIT 1: This code works for me except I am using

numberOfSeconds = 0.5;
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(5);
long interval = (long) (1000* numberOfSeconds); // numberOfSeconds = 10 for you
exec.scheduleAtFixedRate(new savePicTask(), 0, interval, TimeUnit.MILLISECONDS);

And instead of taking a screenshot I am taking a picture with the camera. So I'm not sure why it's not working for you.

Brent McFerrin
  • 528
  • 4
  • 9
  • while loop false is not matter here. When user click on record button it going to take the screen shots of user screen, When user click on stop I will make while flag=flase and stop the thread. Here I want only that why it not make my activity workable. I can not do anything on it. It stuck and backend it takes images – Sohaib Ahmed Aug 25 '14 at 06:57
  • Yeah, I think it's because you are running the screenshots on the main UI thread. You need to run your screenshot logic on a [background thread](http://developer.android.com/guide/components/processes-and-threads.html) (using [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html), [ScheduledExecutorService](http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html), or [ScheduledThreadPoolExecutor](http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html), or something comparable) – Brent McFerrin Aug 25 '14 at 12:46
  • Your code even not capturing one picture. even not creating the folder. – Sohaib Ahmed Aug 26 '14 at 03:49
  • Whoops -- Did you put the ScheduledThreadPoolExecutor as a member outside onCreate()? – Brent McFerrin Aug 26 '14 at 04:07
  • Do you have any output -- errors, print statements, anything? This works for me except I am using it to take a picture every 0.5 seconds and store it to SD card. – Brent McFerrin Aug 26 '14 at 04:28
  • Its not print any log I have check. But I have resolved my issue using time and handler. Thanks Bro for Help. I will run your code and reply your may be I make any mistake in your code. Thanks Again for Help. – Sohaib Ahmed Aug 26 '14 at 04:51