Wednesday, December 21, 2016

How to setup Android Studio for Java 8

Today, I wanted to move one of the project I was working on to Android Studio 2.2 to support Java 8. It's kind of amazing there is not enough information about how to convert an existing project to support Android Studio + Java 8.

1. In your project build.gradle add classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'  So it should be like this

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'me.tatarka:gradle-retrolambda:3.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

2. In your Module build.gradle add

apply plugin: 'me.tatarka.retrolambda'

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}


apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        ..
    }
    buildTypes {
        ...
    }
     
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies {
 ....
}



Wednesday, November 2, 2016

How to fix Arduino WeMos D1 (platform esp8266, package esp8266) is unknown error

fix this go to the folder:

C:\Users\[username]\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\

delete the older version folder and everything works fine again.

Monday, October 3, 2016

Deploying CefSharp with ClickOnce and Could not load file or assembly 'CefSharp.Core.dll

Could not load file or assembly 'CefSharp.Core.dll

oh boy, it is a pain in the ass.

It all started when I decided to use CefSharp in my application. Problem was I was deploying my app though MS ClickOnce and deploying CefSharp and it's dependencies is a pain.

1st lesson

Do not add CefSharp and Xilium.CefGlue to the project. They both use different versions of 'CefSharp.Core.dll' and when you deploy they replace 'CefSharp.Core.dll' with different version rather than the one you used for developments.

2. When you install CefSharp, install cef.redist.x64 and cef.redist.x86 via Package Manager

3. We need to modify the project to

1. Deploy CefSharp and it's all dependancies

2. Deploy CefSharp runtime. Which is  VC++ 2013 for 51.0.0.0

To do that:

 Unload the main project. Right click -> Edit. Just before </project> past following code

<!-- Copy CEF Stuff-->
  <ItemGroup>
    <Content Include="$(SolutionDir)packages\cef.redist.x86.3.2704.1432\CEF\**\*" Exclude="$(SolutionDir)packages\cef.redist.x86.3.2704.1432\CEF\x86\**\*;$(SolutionDir)packages\cef.redist.x86.3.2704.1432\CEF\locales\**\*.pak">
      <Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
      <Visible>false</Visible>
    </Content>
    <Resource Include="Readme.txt" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="$(SolutionDir)packages\cef.redist.x86.3.2704.1432\CEF\**\en-GB.*;$(SolutionDir)packages\cef.redist.x86.3.2704.1432\CEF\**\en-US.*">
      <Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
      <Visible>false</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Content Include="$(SolutionDir)packages\cef.redist.x86.3.2704.1432\CEF\x86\**\*">
      <Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
      <Visible>false</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Content Include="$(SolutionDir)packages\CefSharp.Common.51.0.0\CefSharp\x86\**\CefSharp.BrowserSubprocess.*">
      <Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
      <Visible>false</Visible>
    </Content>
  </ItemGroup>
  <!-- Copy C++ 13 x84 redistributables  -->
  <ItemGroup>
    <Content Include="$(ProjectDir)..\External\Microsoft.VC120.CRT\**\*">
      <Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
      <Visible>false</Visible>
    </Content>
  </ItemGroup>

Note that this project is using cef.redist.x86.3.2704.1432, If you are using x64 you have to modify the above script.

You need to copy Microsoft.VC120.CRT from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\redist\x64\Microsoft.VC120.CRT to a local folder and change "$(ProjectDir)..\External\Microsoft.VC120.CRT\**\*"


Monday, September 26, 2016

How to get the Android device name (Settings->About->DeviceName) in Samsung ?


I wanted to get the device name specified in Settings->About->DeviceName but I did not see any method in Android SDK that you can call to obtain this information. why ? Because this is only specific to Samsung Android devices,  rather than a part of Android itself.

So, how to get the device name ??

1. i tried

BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();

This returns Galexy S5, useless

2.  android.os.Build.MODEL;

returns SM-G900H

3. Had to go deep. then i remembered android has a system values database. which is located at

So I pulled it from my Samsung and took a look

/data/data/com.android.providers.settings/databases/settings.db


So, how to get this using shell

shell@k3g:/ $ settings get system device_name
settings get system device_name
Milky Way

Using java

String deviceName = Settings.System.getString(getContentResolver(), "device_name");

Github project
https://github.com/kakopappa/getdevcicename/blob/master/README.md

Wednesday, August 31, 2016

Simple Android Job Scheduler class

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
    private static final String TAG = "ThreadPool";
    private static final int CORE_POOL_SIZE = 4;
    private static final int MAX_POOL_SIZE = 8;
    private static final int KEEP_ALIVE_TIME = 10; // 10 seconds
    // Resource type
    public static final int MODE_NONE = 0;
    public static final int MODE_CPU = 1;
    public static final int MODE_NETWORK = 2;
    public static final JobContext JOB_CONTEXT_STUB = new JobContextStub();
    ResourceCounter mCpuCounter = new ResourceCounter(2);
    ResourceCounter mNetworkCounter = new ResourceCounter(2);
    // A Job is like a Callable, but it has an addition JobContext parameter.
    public interface Job<T> {
        public T run(JobContext jc);
    }
    public interface JobContext {
        boolean isCancelled();
        void setCancelListener(CancelListener listener);
        boolean setMode(int mode);
    }
    private static class JobContextStub implements JobContext {
        @Override
        public boolean isCancelled() {
            return false;
        }
        @Override
        public void setCancelListener(CancelListener listener) {
        }
        @Override
        public boolean setMode(int mode) {
            return true;
        }
    }
    public interface CancelListener {
        public void onCancel();
    }
    private static class ResourceCounter {
        public int value;
        public ResourceCounter(int v) {
            value = v;
        }
    }
    private final Executor mExecutor;
    public ThreadPool() {
        mExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
                new PriorityThreadFactory("thread-pool",
                android.os.Process.THREAD_PRIORITY_BACKGROUND));
    }
    // Submit a job to the thread pool. The listener will be called when the
    // job is finished (or cancelled).
    public <T> Future<T> submit(Job<T> job, FutureListener<T> listener) {
        Worker<T> w = new Worker<T>(job, listener);
        mExecutor.execute(w);
        return w;
    }
    public <T> Future<T> submit(Job<T> job) {
        return submit(job, null);
    }
    private class Worker<T> implements Runnable, Future<T>, JobContext {
        private static final String TAG = "Worker";
        private Job<T> mJob;
        private FutureListener<T> mListener;
        private CancelListener mCancelListener;
        private ResourceCounter mWaitOnResource;
        private volatile boolean mIsCancelled;
        private boolean mIsDone;
        private T mResult;
        private int mMode;
        public Worker(Job<T> job, FutureListener<T> listener) {
            mJob = job;
            mListener = listener;
        }
        // This is called by a thread in the thread pool.
        public void run() {
            T result = null;
            // A job is in CPU mode by default. setMode returns false
            // if the job is cancelled.
            if (setMode(MODE_CPU)) {
                try {
                    result = mJob.run(this);
                } catch (Throwable ex) {
                    Log.w(TAG, "Exception in running a job", ex);
                }
            }
            synchronized(this) {
                setMode(MODE_NONE);
                mResult = result;
                mIsDone = true;
                notifyAll();
            }
            if (mListener != null) mListener.onFutureDone(this);
        }
        // Below are the methods for Future.
        public synchronized void cancel() {
            if (mIsCancelled) return;
            mIsCancelled = true;
            if (mWaitOnResource != null) {
                synchronized (mWaitOnResource) {
                    mWaitOnResource.notifyAll();
                }
            }
            if (mCancelListener != null) {
                mCancelListener.onCancel();
            }
        }
        public boolean isCancelled() {
            return mIsCancelled;
        }
        public synchronized boolean isDone() {
            return mIsDone;
        }
        public synchronized T get() {
            while (!mIsDone) {
                try {
                    wait();
                } catch (Exception ex) {
                    Log.w(TAG, "ingore exception", ex);
                    // ignore.
                }
            }
            return mResult;
        }
        public void waitDone() {
            get();
        }
        // Below are the methods for JobContext (only called from the
        // thread running the job)
        public synchronized void setCancelListener(CancelListener listener) {
            mCancelListener = listener;
            if (mIsCancelled && mCancelListener != null) {
                mCancelListener.onCancel();
            }
        }
        public boolean setMode(int mode) {
            // Release old resource
            ResourceCounter rc = modeToCounter(mMode);
            if (rc != null) releaseResource(rc);
            mMode = MODE_NONE;
            // Acquire new resource
            rc = modeToCounter(mode);
            if (rc != null) {
                if (!acquireResource(rc)) {
                    return false;
                }
                mMode = mode;
            }
            return true;
        }
        private ResourceCounter modeToCounter(int mode) {
            if (mode == MODE_CPU) {
                return mCpuCounter;
            } else if (mode == MODE_NETWORK) {
                return mNetworkCounter;
            } else {
                return null;
            }
        }
        private boolean acquireResource(ResourceCounter counter) {
            while (true) {
                synchronized (this) {
                    if (mIsCancelled) {
                        mWaitOnResource = null;
                        return false;
                    }
                    mWaitOnResource = counter;
                }
                synchronized (counter) {
                    if (counter.value > 0) {
                        counter.value--;
                        break;
                    } else {
                        try {
                            counter.wait();
                        } catch (InterruptedException ex) {
                            // ignore.
                        }
                    }
                }
            }
            synchronized (this) {
                mWaitOnResource = null;
            }
            return true;
        }
        private void releaseResource(ResourceCounter counter) {
            synchronized (counter) {
                counter.value++;
                counter.notifyAll();
            }
        }
    }
}

Friday, August 26, 2016

How to run a single instance of the application or bring app to foreground using C#

 static class Program
    {
        [STAThread]
        static void Main()
        {
            bool createdNew;
            using (new Mutex(true, "MyApp", out createdNew))
            {
                if (createdNew) {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    var mainClass = new SynGesturesLogic();
                    Application.ApplicationExit += mainClass.tray_exit;
                    Application.Run();
                }
                else
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName).Where(process => process.Id != current.Id))
                    {
                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
            }
        }
    }

Thursday, August 11, 2016

How to get the activity on top of the stack using android shell (adb shell)



adb shell dumpsys activity activities | busybox sed -En -e '/Stack #/p' -e '/Running activities/,/Run #0/p'

Thursday, August 4, 2016

How to check whether an audio file is Silk file ?

private static boolean isSilkV3File(String filePath) {
RandomAccessFile rFile = null;

        try {
            rFile = new RandomAccessFile(filePath, "r");
         
            byte[] bArr = new byte[9];
            rFile.seek(1);
            rFile.read(bArr, 0, 9);
         
            String headStr = new String(bArr);
         
            if (headStr.endsWith("#!SILK_V3")) {
                return true;
            }
            else {
            return false;
            }
         
        } catch (Exception e3) {
                }
        finally {
        if(rFile != null) {
        try { rFile.close(); } catch (IOException e) { }
        }
        }
     
return false;
}

Tuesday, August 2, 2016

How to view table schema in SQLite

Normally you can

sp_help '<TableName>' will give you the structure of a table in SQL Server but how to do this in SQLite ?

Use

PRAGMA table_info(<table_name>)

eg:
PRAGMA table_info(ImgInfo2)

Tuesday, July 12, 2016

How to add current path to .bashrc


Go to the path and then:

echo "export PATH=$(pwd):\${PATH}" >> ~/.bashrc

Wednesday, March 23, 2016

How to make a rounded bitmap in Android

    public static Bitmap getRoundedBitmap(Bitmap bitmap, int i, int i2) {
        if (bitmap == null) {
            return null;
        }
        Bitmap createBitmap = Bitmap.createBitmap(i, i2, bitmap.getConfig());
        Canvas canvas = new Canvas(createBitmap);
        Paint paint = new Paint();
        canvas.drawARGB(0, 0, 0, 0);
        paint.setAntiAlias(true);
        canvas.drawOval(0.0f, 0.0f, (float) i, (float) i2, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float min = Math.min(((float) width) / ((float) i), ((float) height) / ((float) i2));
        int i3 = (int) ((((float) i) * min) / 2.0f);
        int i4 = (int) ((min * ((float) i2)) / 2.0f);
        canvas.drawBitmap(bitmap, new Rect((width / 2) - i3, (height / 2) - i4, (width / 2) + i3, (height / 2) + i4), new RectF(0.0f, 0.0f, (float) i, (float) i2), paint);
        return createBitmap;
    }

Sunday, February 28, 2016

How to change the auto rotation feature to potrait using adb shell ?

content insert --uri content://settings/system --bind name:s:accelerometer_rotation --bind value:i:0

Thursday, February 4, 2016

how to turn mobile data on or off using adb shell root

root@j2lte:/ # svc data
Control mobile data connectivity

usage: svc data [enable|disable]
         Turn mobile data on or off.


root@j2lte:/ # svc data enable

how to switch off or reboot phone using root ?

root@j2lte:/ # svc power
Control the power manager

usage: svc power stayon [true|false|usb|ac|wireless]
         Set the 'keep awake while plugged in' setting.
       svc power reboot [reason]
         Perform a runtime shutdown and reboot device with specified reason.
       svc power shutdown
         Perform a runtime shutdown and power off the device.

root@j2lte:/ # svc power reboot becauseican

Monday, February 1, 2016

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

I am using a .dll file that is written using C++ in my C# application. When I deployed it test PC I started seeing this error in Event Log.


So, I used Dependency Walker to check the missing dependencies and I was missing `msvcp110d.dll` and `msvcr110d.dll` in the test PC

I copied these two files from my dev PC to test PC's `C:\Windows\SysWOW64`  PC and worked!

Saturday, January 9, 2016

Transmission daemon overwrites settings.json to the default in Raspberry Pi

sudo /etc/init.d/transmission-daemon stop

cd /var/lib/transmission-daemon/info
sudo nano settings.json

Change "rpc-authentication-required": false,

cd /etc/transmission-daemon
sudo nano settings.json

Change "rpc-authentication-required": false,


sudo /etc/init.d/transmission-daemon start

Wednesday, January 6, 2016

Android sh script error "[: not found" or incorrect systax if;

One of the scripts i was working suddenly starting showing Android sh script error "[: not found" or incorrect systax if; errors out of blue. I couldn't figure out what just went wrong.


 Reson is file format and line ending. To fix this in NotePad ++

Edit -> EOL Conversion -> Unix
Encoding -> Encode in ANSI



Tuesday, January 5, 2016

How to write to Android LogCat via adb shell ?

log  -p i -t yourtag "see this in logcat"


yourtag = is the tag for LogCat