2011年4月29日 星期五

[Eclipse] Eclipse快速鍵整理

快速鍵
  • F11: Debug
  • Ctrl + F11: Run.
  • Ctrl + Shift + B: Toggle Breakpointer.
  • Ctrl + Shift + F: Format.
  • Ctrl + Mouse left click: View Source Code.
  • Ctrl + /: Add Comment.

延伸閱讀

[Java] What is an interface in Java

Java Interface:
1. 由於Java沒有Class多重繼承,為了讓物件具有多種型態,可以用Interface(介面)的達到多重繼承的需求。
2. 介面方法宣告預設都是"public",有沒有加public預設仍是public。
3. 介面宣告預設都是abstract,有沒有加abstract預設仍是abstract。
4. 當定義類別時,可以使用"implements"關鍵字來指定要實作哪個介面,介面中所有定義的方法都要實作。
5. 由於介面中的方法預設都是public,所以實作介面的類別中,方法必須宣告為public,否則無法通過編譯。


public interface IRequest {
  public abstract void execute(); // 可以用 void execute(); 省略public或abstract,其意義相同。
} 

public class HelloRequest implements IRequest {
  private String name;
  public HelloRequest(String name) 
  {
    this.name = name;
  }

  public void execute() {
    System.out.printf("Hello! %s!%n", name);
  }
} 

實作多個介面的方式: 

public class 類別名稱 implements 介面1, 介面2, 介面3 { 
    // 介面實作 
}

介面進行繼承的方式: 

public interface 名稱 extends 介面1, 介面2 { 
    // ... 
} 


References:

2011年4月27日 星期三

[Android] Build NDK Environment

NDK是什麼?
The Android NDK is a toolset that lets you embed components that make use of native code in your Android applications.

安裝NDK

Step 1:安裝Cygwin
  • 下載點:到http://cygwin.com/install.html下載setup.exe
  • Cygwin Setup: Next
  • Cygwin Setup - Choose Installation Type: Install from Internet > Next
  • Cygwin Setup - Choose Installation Directory: All Users > Next
  • Cygwin Setup - Select Local Package Directory > Next
  • Cygwin Setup - Select Connection Type: Direct Connection > Next
  • Cygwin Setup - Choose Download Site(s): ftp:/ftp.ntu.edu.tw > Next
  • Cygwin Setup - Select Packages as below > Next


  • Launch Cygwin and run sure "gcc -v" and "make -v" to verify if it works correctly.
$ gcc -v
Reading specs from /usr/lib/gcc/i686-pc-cygwin/3.4.4/specs
Configured with: /managed/gcc-build/final-v3-bootstrap/gcc-3.4.4-999/configure --verbose --program-suffix=-3 --prefix=/usr --exec-prefix=/us
r --sysconfdir=/etc --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --enable-languages=c,ada,c++,d
,f77,pascal,java,objc --enable-nls --without-included-gettext --enable-version-specific-runtime-libs --without-x --enable-libgcj --disable-j
ava-awt --with-system-zlib --enable-interpreter --disable-libgcj-debug --enable-threads=posix --enable-java-gc=boehm --disable-win32-registr
y --enable-sjlj-exceptions --enable-hash-synchronization --enable-libstdcxx-debug
Thread model: posix
gcc version 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)

$ make -v
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i686-pc-cygwin

Step 2:安裝NDK

  • 下載點:到http://developer.android.com/sdk/ndk/index.html 下載Android NDK for Windows
  • Cygwin Setup: Next
  • Cygwin Setup - Choose Installation Type: Install from Internet > Next
  • Cygwin Setup - Choose Installation Directory: All Users > Next
  • Cygwin Setup - Select Local Package Directory > Next
  • Cygwin Setup - Select Connection Type: Direct Connection > Next
  • Cygwin Setup - Choose Download Site(s): ftp:/ftp.ntu.edu.tw > Next
  • Cygwin Setup - Select Packages as below > Next
  • 然後到C:\cygwin\home\"使用者名稱" 目錄下,用windows編輯器編輯.bash_profile :
在最後一行後加入下面四行,然後存檔:
PATH=/android-ndk-r5:${PATH}
NDK_ROOT=/android-ndk-r5
NDK_Sample=/android-ndk-r5/samples
export PATH NDK_ROOT NDK_Sample
(NDK_Sample是指定你的JNI程式所要放置的目錄,這邊我我指定到/android-ndk-r5/samples,這個參數會在Eclipse的C編譯中使用到。)
  • 開啟Cygwin Bash Shell到/android-ndk-r5/samples/hello-jni/目錄下,執行ndk-build
vince_huang@VinceH-DT ~
$ cd /android-ndk-r5/samples/hello-jni/

vince_huang@VinceH-DT /android-ndk-r5/samples/hello-jni
$ ndk-build
Gdbserver      : [arm-linux-androideabi-4.4.3] libs/armeabi/gdbserver
Gdbsetup       : libs/armeabi/gdb.setup
Install        : libhello-jni.so => libs/armeabi/libhello-jni.so

Step 2:安裝Eclipse CDT(C/C++ Development Tool)

  • Eclipse Help > Install New Software... > Add...
  • Name: CDT
  • Location: http://download.eclipse.org/tools/cdt/releases/galileo
  • 安裝Eclipse C/C++ Development Tools
  • 安裝CDT GNU Toolchain Build Support
  • 安裝CDT GNU Toolchain Debug Support
  • 安裝CDT Utilities
  • 安裝Eclipse C/C++ Development Platform
  • 安裝完成後,Eclipse會要求重新開啟Eclipse,重開Eclipse後便可以在Eclipse中編輯C/C++程式。

相關連結

[Android] MediaStore

The Media provider contains meta data for all available media on both internal and external storage devices.

A Example:

String[] projection = new String[] {
  Images.ImageColumns._ID,
  Images.ImageColumns.BUCKET_DISPLAY_NAME,
  Images.ImageColumns.BUCKET_ID,
  Images.ImageColumns.DATE_TAKEN,
  Images.ImageColumns.DESCRIPTION,
  Images.ImageColumns.IS_PRIVATE,
  Images.ImageColumns.LATITUDE,
  Images.ImageColumns.LONGITUDE,
  Images.ImageColumns.MINI_THUMB_MAGIC,
  Images.ImageColumns.ORIENTATION,
  Images.ImageColumns.PICASA_ID,
  Images.ImageColumns.DATA,
  Images.ImageColumns.DATE_ADDED,
  Images.ImageColumns.DATE_MODIFIED,
  Images.ImageColumns.DISPLAY_NAME,
  Images.ImageColumns.MIME_TYPE,
  Images.ImageColumns.SIZE,
  Images.ImageColumns.TITLE
};

// We can use the following query method to query data.
//Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);

Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);

int count = cursor.getCount();

System.out.println("count = " + count);

for (int i=0; i<count; i++)
{
  cursor.moveToPosition(i);
  int columnSize = cursor.getColumnCount();
  for (int j=0; j<columnsize; j++)
  {
    System.out.println("index = " + j + " " + cursor.getColumnName(j) + " = " + cursor.getString(j));
  }
}

Reference:

2011年4月25日 星期一

[JavaScript] JSLint 文斯不負責報導

JSLint是一套可以幫你檢查你的JavaScript程式中語法和語意是否有錯誤的工具。

接下來我們來看看JSLint能幫我們什麼忙?

全域變數(Global Variables)
JavaScript 中只要變數使用前沒有先用var宣告過,該變數就會是全域變數。這可能會導致變數名字拼錯等問題發生。JSLint會檢查是否所有變數和函數在它被使用前應該要先宣告過。 這可以使程式更容易閱讀。

分號(Semicolon)
JavaScript類似C語言的語法,因此需要使用分號來分隔的程式陳述(Statement)。在JavaScript中,可以換行空格,也可以作為一個分號做為程式陳述的結尾,但這可能會導致錯誤發生。因此JSLint會檢查每個程式陳述之後 , 除了for、function、if、switch、try和while。 JSLint 不希望看到不必要的分號或空語句。

逗號(Comma)逗號運算元可以用於程式技巧表達上。它也可能掩蓋一些程式錯誤。JSLint會檢查是否逗號只作為分隔符號,且不能作為運算元(除在程式初始化和for的程式陳述上)。它不希望看到省略元素在陣列字元上。也不應該有額外的逗號。一個逗號不應該出現在陣列或物件的最後一個元素後,因為它在某些瀏覽器上會出錯。

程式範圍(Scope)
在許多程式語言中,程式區塊定義了程式的範圍。 在程式區塊中定義的變數在程式區塊外則是不可見的。在JavaScript中,程式區塊則不會定義了程式的範圍。只有函數才有程式範圍的概念。如果一個變數在函數中任何地方被定義的,則該變數在函數中任何地方皆為可用的。因此JavaScript的程式區塊易造成混淆。JSLint會檢查是否程式區塊只在function、if、switch、while、for、do和try中。在程式區塊的範圍中,通常變數的量定義是在第一次使用時。但由於JavaScript沒有程式範圍的概念,因此最好在函數開始就宣告所有的變數,且最好一行只宣告一個變數。

程式區塊(Block)
JSLint會檢查是否只有if、while、do和for的程式陳述有程式區塊。

表達式陳述(Expression Statements)
  1. For in: 使用for in陳述可以列舉變數中所有的元素,但確保不會存取到不想存取的屬性,最好在for in中用hasOwnProperty來檢查一下。
  2. switch: 在下一個case或default之前的陳述必須是break、return或throw。
  3. var: 每一個變數或函數皆需要使用var宣告,且只能宣告一次,但參數(parameters)、引數(arguments)及程式區塊則不用。
  4. with: 不要使用with,它容易造成混淆。
  5. =: 邏輯判斷時不要使用=。
  6. == and !=: 與null、0、undefined、true、false這些值比較時,一定要用===和!==,因為 JavaScript 有神祕的型別轉換,讓你的 null==undefined 但是null != false,要判斷是否是以上列舉值的其中任一種時,就用===和!==吧,如果只是要 true/false 判斷,則可以用==和!=。
  7. labels: 只能在break有作用的程式區塊(ex: switch, while, do, and for)允許使用label。
  8. Unreachable Code: return、break、continue或throw陳述後必須接著}、case或 default。以避免產生執行不到的程式碼。
  9. Confusing Pluses and Minuses: 不要使用+後接+或++,-後接-或--的情形。
  10. ++ and --: 不要使用++或--。
  11. Bitwise Operators: 不要使用bit運算元。
  12. eval is evil: 不要使用eval。
  13. void: 在JavaScript中void代表undefined,因此不要使用void。
  14. Regular Expressions: 正規表示法之前的字元需為(、=、:或,。
  15. Constructors and new: 不要使用new在Number、String或Boolean上,也不要使用new在物件(Object)或陣列(Array)上。可以使用 {} 建立物件, [] 建立陣列。
  16. Unsafe Characters: \u0000-\u001f、\u007f-\u009f、\u00ad、\u0600-\u0604、\u070f、\u17b4、\u17b5、\u200c-\u200f、\u2028-\u202f、\u2060-\u206f、\ufeff、\ufff0-\uffff為不安全字元,使用時需使用脫離(Escape)函數處理。

References:

2011年4月22日 星期五

[Java] ThreadPoolExecutor

一個任務通過execute(Runnable)方法被加入到執行緒池,任務就是一個Runnable類型的物件,任務的執行方法就是Runnable類型物件的run()方法。

當一個任務通過execute(Runnable)方法欲加入到執行緒池時:

  • 如果此時執行緒池中的數量小於corePoolSize,即使執行緒池中的執行緒都處於空閒狀態,也要新增新的執行緒來處理被加入的任務。
  • 如果此時執行緒池中的數量等於 corePoolSize,但是緩衝佇列 workQueue未滿,那麼任務被放入緩衝佇列。
  • 如果此時執行緒池中的數量大於corePoolSize,緩衝佇列workQueue滿,並且執行緒池中的數量小於maximumPoolSize,建新的執行緒來處理被添加的任務。
  • 如果此時執行緒池中的數量大於corePoolSize,緩衝佇列workQueue滿,並且執行緒池中的數量等於maximumPoolSize,那麼通過 handler所指定的策略來處理此任務。

也就是說處理任務的優先順序為:
  • 核心執行緒corePoolSize、任務佇列workQueue、最大執行緒maximumPoolSize,如果三者都滿了,使用handler處理被拒絕的任務。
  • 當執行緒池中的執行緒數量大於 corePoolSize時,如果某執行緒閒置時間超過keepAliveTime,執行緒將被終止。這樣,執行緒池可以動態的調整池中的執行緒數。
unit可選的參數為java.util.concurrent.TimeUnit中的幾個靜態屬性:
  • NANOSECONDS
  • MICROSECONDS
  • MILLISECONDS
  • SECONDS。

workQueue常用的是:
  • java.util.concurrent.ArrayBlockingQueue

handler有四個選擇:
  • ThreadPoolExecutor.AbortPolicy():丟出java.util.concurrent.RejectedExecutionException異常
  • ThreadPoolExecutor.CallerRunsPolicy():重試加入當前的任務,他會自動重複調用execute()方法
  • ThreadPoolExecutor.DiscardOldestPolicy():放棄最舊的任務
  • ThreadPoolExecutor.DiscardPolicy():放棄當前的任務

Constructor: Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and handler.

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue)


核心執行緒池大小(corePoolSize)
  • 池中所保存的執行緒數,包括空閒執行緒。
最大執行緒池大小(maximumPoolSize)
  • maximumPoolSize - 池中允許的最大執行緒數。
工作存活時間(KeepAliveTime)
  • keepAliveTime - 當執行緒數大於核心時,此為終止前多餘的空閒執行緒等待新任務的最長時間。
工作存活時間(unit)
  • unit - keepAliveTime 參數的時間單位。
工作佇列(workQueue)
  • workQueue - 執行前用於保持任務的佇列。此佇列僅保持由 execute 方法提交的 Runnable 任務。
import java.util.concurrent.*;
import java.util.*;
 
class MyThreadPoolExecutor
{
    int poolSize = 2;
 
    int maxPoolSize = 2;
 
    long keepAliveTime = 10;
 
    ThreadPoolExecutor threadPool = null;
 
    final ArrayBlockingQueue queue = new ArrayBlockingQueue(
            5);
 
    public MyThreadPoolExecutor()
    {
        threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
                keepAliveTime, TimeUnit.SECONDS, queue);
 
    }
 
    public void runTask(Runnable task)
    {
        // System.out.println("Task count.."+threadPool.getTaskCount() );
        // System.out.println("Queue Size before assigning the
        // task.."+queue.size() );
        threadPool.execute(task);
        // System.out.println("Queue Size after assigning the
        // task.."+queue.size() );
        // System.out.println("Pool Size after assigning the
        // task.."+threadPool.getActiveCount() );
        // System.out.println("Task count.."+threadPool.getTaskCount() );
        System.out.println("Task count.." + queue.size());
 
    }
 
    public void shutDown()
    {
        threadPool.shutdown();
    }
 
    public static void main(String args[])
    {
        MyThreadPoolExecutor mtpe = new MyThreadPoolExecutor();
        // start first one
        mtpe.runTask(new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        System.out.println("First Task");
                        Thread.sleep(1000);
                    } catch (InterruptedException ie)
                    {
                    }
                }
            }
        });
        // start second one
        /*
         * try{ Thread.sleep(500); }catch(InterruptedException
         * ie){}
         */
        mtpe.runTask(new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        System.out.println("Second Task");
                        Thread.sleep(1000);
                    } catch (InterruptedException ie)
                    {
                    }
                }
            }
        });
        // start third one
        /*
         * try{ Thread.sleep(500); }catch(InterruptedException
         * ie){}
         */
        mtpe.runTask(new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        System.out.println("Third Task");
                        Thread.sleep(1000);
                    } catch (InterruptedException ie)
                    {
                    }
                }
            }
        });
        // start fourth one
        /*
         * try{ Thread.sleep(500); }catch(InterruptedException
         * ie){}
         */
        mtpe.runTask(new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        System.out.println("Fourth Task");
                        Thread.sleep(1000);
                    } catch (InterruptedException ie)
                    {
                    }
                }
            }
        });
        // start fifth one
        /*
         * try{ Thread.sleep(500); }catch(InterruptedException
         * ie){}
         */
        mtpe.runTask(new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        System.out.println("Fifth Task");
                        Thread.sleep(1000);
                    } catch (InterruptedException ie)
                    {
                    }
                }
            }
        });
        // start Sixth one
        /*
         * try{ Thread.sleep(500); }catch(InterruptedException
         * ie){}
         */
        mtpe.runTask(new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        System.out.println("Sixth Task");
                        Thread.sleep(1000);
                    } catch (InterruptedException ie)
                    {
                    }
                }
            }
        });
        mtpe.shutDown();
    }
 
}
Reference: