Wednesday, March 29, 2017

How to make a .jar out from an Android Studio project

http://stackoverflow.com/questions/21712714/how-to-make-a-jar-out-from-an-android-studio-project

http://dominoc925.blogspot.com/2015/09/how-to-create-and-use-jar-archive-using.html

http://toastdroid.com/2014/03/28/customizing-your-build-with-gradle/

http://tools.android.com/tech-docs/new-build-system/user-guide

Monday, March 27, 2017


system/bin/screencap -p crash.png


shell@DemeterUHD:/sdcard/Pictures $ screencap --help
screencap: invalid option -- -
usage: screencap [-hp] [-d display-id] [FILENAME]
   -h: this message
   -p: save the file as a png.
   -d: specify the display id to capture, default 0.
If FILENAME ends with .png it will be saved as a png.
If FILENAME is not given, the results will be printed to stdout.

splinter wait page to load

class wait_for_page_load(object):

    def __init__(self, browser):
        self.browser = browser

    def __enter__(self):
        self.old_page = self.browser.find_element_by_tag_name('html')

    def page_has_loaded(self):
        new_page = self.browser.find_element_by_tag_name('html')
        return new_page.id != self.old_page.id

    def __exit__(self, *_):
        wait_for(self.page_has_loaded)

with wait_for_page_load(browser):
    browser.find_element_by_link_text('my link').click()

Tuesday, March 21, 2017

android timer ui thread

import java.util.Timer;
import java.util.TimerTask;

    private Timer myTimer;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            @Override            public void run() {
                TimerMethod();
            }
        }, 0, 1000);

    }


    private void TimerMethod()
    {
        //This method is called directly by the timer        //and runs in the same thread as the timer.        this.runOnUiThread(Timer_Tick);
    }

    private Runnable Timer_Tick = new Runnable() {
        public void run() {
            //This method runs in the same thread as the UI.            //Do something to the UI thread here            Log.e(TAG, "********************************");
        }
    };

Monday, March 20, 2017

android media player black screen

            mMediaPlayer = new MediaPlayer(this, false);
            mMediaPlayer.setDataSource(filePath);
            mSurfaceHolder.setKeepScreenOn(true);
            mMediaPlayer.setDisplay(mSurfaceHolder);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnSeekCompleteListener(this);
            mMediaPlayer.setOnErrorListener(this);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnVideoSizeChangedListener(this);


The only working tricky workaround for this problem:

Description: Post a delayed Runnable to check onPrepared status, if failed, reinitialize the engine and remove the callback in case of onPrepared get called
The very important note is that, onPause is called after the failure so do not remove callbacks there and instead use surfaceDestroyed method of SurfaceHolder.Callback interface




 private void OpenMedia(String filePath, long lastPosition) {
        doCleanUp();

        handler.postDelayed(onPreparedErrorInvestigatorRunnable, 5000);

         Log.d(TAG, "Starting MediaPlayer initialization");
         mMediaPlayer = new MediaPlayer(this, false);
           ...
 }

    @Override
    public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG, "onPrepared called");

        // no investigation required
        handler.removeCallbacks(onPreparedErrorInvestigatorRunnable);

       ...
    }

   @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        Log.d(TAG, "PlayerSurface destroyed");
        handler.removeCallbacks(onPreparedErrorInvestigatorRunnable);
    }

    Runnable onPreparedErrorInvestigatorRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "Vitamio Initialization Error Detected, Retrying ...");
            releaseMediaPlayer();
            OpenMedia(lastPlaybackInfo.videoFilePath, lastPlaybackInfo.lastPosition);
        }
    };

Wednesday, March 8, 2017

screenshot method / base64

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Base64;
import android.view.View;

import java.io.ByteArrayOutputStream;

/**
 * <h1>Utilities Class</h1>
 * CommonUtils class under common package provides several useful methods
 * that can be used by any of applications that imports this package
 * such as capturing screenshot and encoding/decoding data from/to Base64.
 *
 * @version 1.0
 */

public class CommonUtils {
    private Context mContext;
    private Activity mActivity;
    private static final int SCALED_PIXEL = 256;

    public CommonUtils(Context context, Activity activity) {
        mContext = context;
        mActivity = activity;
    }

    private Bitmap getScreenshot(boolean fullscreen) {
        View view = mActivity.getWindow().getDecorView().getRootView();
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        if (!fullscreen) {
            bitmap = Bitmap.createScaledBitmap(bitmap, SCALED_PIXEL, SCALED_PIXEL, false);
        }

        return bitmap;
    }

    private byte[] convertBitmap2Bytes(Bitmap bitmap) {
        byte[] byteArray;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byteArray = stream.toByteArray();

        return byteArray;
    }

    private String encodeImg2B64(byte[] image) {
        return Base64.encodeToString(image, Base64.DEFAULT);
    }

    /**
     * This method captures a screenshot and encodes the data to Base64
     * @return String Base64 encoded string data from captured screenshot
     */
    public String getB64FromScreenshot() {
        return encodeImg2B64(convertBitmap2Bytes(getScreenshot(false)));
    }

    /**
     * This method is used to get Base64 decoded byte[] data from given Base64 encoded string data
     * @param screenshot Base64 encoded string data
     * @return data Base64 decoded byte[] data
     */
    public byte[] getScreenshotFromB64(String screenshot) {
        byte[] data = Base64.decode(screenshot, Base64.DEFAULT);
        return data;
    }
}

android external storage environment

File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "shot_from_service.png");

Monday, March 6, 2017

android runtime permissions


private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 0x1000;

private void requestPermissions() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Log.e(TAG, "shouldShowRequestPermissionRationale()");
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            Log.e(TAG, "requestPermissions()");
        }
    }
}

@Overridepublic void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE:
            // If request is cancelled, the result arrays are empty.            if (grantResults.length > 0                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "permission Granted");
            } else {
                Log.e(TAG, "permission Denied");
            }
            break;
        default:
            break;
    }
}