2011年12月20日

笑會感染喔!

Lachen in der U-Bahn - www.lachen-verbindet.de

這是不是大腦的鏡像神經元發作呀?
看別人那麼開懷大笑,自己也會不由自主地跟著起笑 :-)

2011年12月18日

Android: 檢查SD卡可用容量MB

public boolean isAvaiableSpace(float sizeMB){
 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
   String sdcard =Environment.getExternalStorageDirectory().getPath();
   StatFs statFs =new StatFs(sdcard);
   long blockSize=statFs.getBlockSize();
   long ablocks  =statFs.getAvailableBlocks();
   float available=(float)((ablocks*blockSize)/(1024*1024));
   if (sizeMB > available)
       return false;
   else
       return true;
 }
 return false;
}

2011年12月14日

Java: 刪除整個目錄(子目錄和檔案)

public boolean deleteDir(File dir) {
   if (dir.isDirectory()) {
       File[] files = dir.listFiles();
       for (int i=0;i<files.length;i++) { 
            if (!deleteDir(files[i]))
               return false;
       }
   }
   //目錄現在清空了可以刪除
   return dir.delete();
}

Progressive Education Why It’s Hard to Beat, But Also Hard to Find: 進步教育部份筆記

Progressive Education
Why It’s Hard to Beat, But Also Hard to Find (By Alfie Kohn)
進步教育本身並無一個固定的定義,這似乎和它反對一致性和標準化的聲譽相符。任何兩個自認了解此"傳統"的教育工作者,也可能會以不同的角度來看待,或者至少會對哪些是最重要的有爭議.
和多位進步教育工作者交談後,其實你會開始注意到某些弔詭:有些人專注於個別學生的獨特需要,而有些人強調學習者社群的重要,有些人形容學習為一個過程,旅程比目的地重要,而另一些認為學習任務應該導致可共享的真實產物。
它是什麼?

2011年12月13日

牛頓手稿數位化 Cambridge Digital Library - University of Cambridge

Cambridge Digital Library - University of Cambridge:

"Cambridge University Library contains evidence of some of the greatest ideas and discoveries over two millennia. We want to make our collections accessible to anyone, anywhere in the world with an internet connection and a thirst for knowledge." —Anne Jarvis, University Librarian


Explore the British Library here

2011年11月30日

Android: AsyncTask 非同步任務

AsyncTask 讓我們可在UI thread中執行非同步工作。它在worker thread中執行需長時間的作業,然後將結果傳回使用介面緒,省掉我們親自處理Thread或Handlers的麻煩。

2011年11月23日

Piano Society - Free Classical Recordings

Piano Society - Free Classical Recordings:

2011年11月21日

只需兩套公式: THE ULTIMATE SOLUTION

RUBIK's CUBE: THE ULTIMATE SOLUTION

2011年10月31日

Anroid: 簡易Yes/No AlertDialog 對話盒

當程式需要和使用者作簡單的即時互動時,一個簡單的對話盒通常就能滿足所需.
底下是簡單好用的對話盒,可以回應Yes/No按鈕

2011年10月29日

Android: 產生MD5

檔案的MD5碼可用來檢查檔案是否有毀損或異動,
底下的作法,在讀取檔案的同時,進行MD5計算, 省時又方便!

Android: 解壓縮檔zip

當程式從網站下載檔案時,為了節省頻寬,通常會對檔案進行壓縮.
Java本身就有處理Zip/Unzip的API.見底下程式碼:

Android: TTS Engine 範例 RobotSpeakTtsService.java | Android Developers

RobotSpeakTtsService.java | Android Developers:
Android v4.0提供製作TTS engine的API,棒吧!

2011年10月20日

Android: ColorPickerDialog 選不到黑色

原來在Android的原始Demo程式中修改mColors的設定,加入黑色即可。
一口氣加了3個黑色!(別再跟我說選不到了吧:-)
mColors = new int[] {
    0xFFff0000,0xFFff00ff,0xFF000000,0xFF0000ff,0xFF00ffff,
    0xFF000000,0xFF00ff00,0xFFffff00, 0xFF000000,0xFFff0000
};
注意頭尾值必須一致,才不會顏色突然斷掉。 想要白色也沒問題,只要加入0xFFFFFFFF即可!

Android: Android Beam (NFC近場通訊)

翻譯自Android Developer

    Android Beam基於NFC (Near Field Communication 近場通訊) 技術,只需讓兩隻NFC啟動的裝置靠近,使用者就能立刻分享使用中app的資訊。當裝置在作用範圍內(幾公分),系統會建立NFC連結並顯示一個分享使用介面。只需觸摸螢幕就能分享他們在其他裝置看到的任何東西 (見底下示範影片)

2011年10月19日

Android: 設定Paint.setTextSize() 的大小單位

若不用底下的方法設定大小,則不同解析度的裝置, 其畫出來的字體大小會差異極大!
float dips = 16.0f;
// Convert the dips to pixels
final float scale = getResources().getDisplayMetrics().density;
int ps = (int) (dips * scale + 0.5f);
Paint imagePaint = new Paint();
imagePaint.setTextSize(ps);

Android: EditText和EditTextPreference輸入格式

在AndroidManifest.xml中指定EditText和EditTextPreference的輸入格式,,
可以節省很多不必要的檢查動作!
//文字
android:inputType=
"none"
"text"
"textCapCharacters"
"textCapWords"
"textCapSentences"

2011年10月17日

Android: WebView 設定背景background

//設定透明色
webView.setBackgroundColor(0);   
//或在AndroidManifest.xml中指定也可以
webView.setBackgroundResource(R.drawable.yourImage); 
//或產生一個drawable的物件 webView.setBackgroundResource(d);

2011年10月13日

Java: 文數字排序

出自 Kushal's Java Blog | Software Engineering Blog » Blog » Alphanumeric String Sorting In Java (Implementation):

用Java的基本字串排序,來排序底下字串,
名詞11 名詞1 名詞3 名詞10 名詞2 
變成
名詞1 名詞10 名詞11 名詞2 名詞3


用上面的Alphanumeric String Sorting可以得到我們想要的
名詞1 名詞2 名詞3 名詞10 名詞11 


2011年10月12日

Java: Split分割字串

看起來很簡單又好用的函數,竟讓我冒了一身冷汗,花了一會兒才知道自己錯在哪裡?
第一次用"@"切字串,矇到了ok。
第二次用"^"切字串,出不來;嚇了一跳。
第三次用"$"切字串,還是出不來;差點昏倒 :-(
連忙Google看是怎麼回事?
原來其分隔參數是Regular Expression正則表示式,所以底下那些符號都必須用 避開。
剛好 \ 也在其中所以必須用兩個 \\
例如用"^"切字串,必須寫成 TestString.split("\\^");
^ $ * + ? { }.[ ] ( ) \ | \d \D \w \W \s \S

2011年10月11日

Android: meta-data 使用

出處:android meta-data 使用详解 - - ITeye技术网站:

應用程式可以放些資料在AndroidManifest.xml中的宣告<activity> <activity-alias> <service> <receiver>四个元素中。Meta-data在Activity之間用來判斷某些事物時很有用。
<meta-data android:name="zoo" android:value="@string/kangaroo" />
程式中取得的方式
ActivityInfo ai = activity.getPackageManager().getActivityInfo(componentName, PackageManager.GET_META_DATA); 
String zoo = ai.metaData.getString("zoo"); 
Toast.makeText(this, "meta:"+zoo, 1).show();

2011年10月4日

被胡蜂螫了

不知如何形容那一陣陣的刺痛,只說得出好痛.
周末10/1全家和學校其他家庭一起去南澳溯溪,途中一隻蜂突然飛入車中,
靠窗小朋友抱頭躲著,我這自作聰明的大人,見狀急忙用手去揮趕...
沒錯,就被螫在大拇指上還停在上面不肯走哩,我急忙用左手捏起它,往窗外扔去.
是中午烤肉時煙燻大拇指太香了是嗎 :-)

2011年10月1日

連結:C2DM Android上雲端發訊息

Android Cloud to Device Messaging Framework - Google Projects for Android:
節錄自上述網址

Introduction

Here are the primary characteristics of Android Cloud to Device Messaging (C2DM):
  • It allows third-party application servers to send lightweight messages to their Android applications. The messaging service is not designed for sending a lot of user content via the messages. Rather, it should be used to tell the application that there is new data on the server, so that the application can fetch it.
  • C2DM makes no guarantees about delivery or the order of messages. So, for example, while you might use this feature to tell an instant messaging application that the user has new messages, you probably would not use it to pass the actual messages.
  • An application on an Android device doesn’t need to be running to receive messages. The system will wake up the application via Intent broadcast when the the message arrives, as long as the application is set up with the proper broadcast receiver and permissions.
  • It does not provide any built-in user interface or other handling for message data. C2DM simply passes raw message data received straight to the application, which has full control of how to handle it. For example, the application might post a notification, display a custom user interface, or silently sync data.
  • It requires devices running Android 2.2 or higher that also have the Market application installed. However, you are not limited to deploying your applications through Market.
  • It uses an existing connection for Google services. This requires users to set up their Google account on their mobile devices.

2011年9月29日

Android: 從Content Resolver取得Media (II)

Android Developer: Content Provider
底下節錄翻譯自上面:
//Use ContentUris to produce the base URI for the contact with _ID= 23.
Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
// Alternatively, use the Uri method to produce the base URI.
// It takes a string rather than an integer.
Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
// Then query for this specific record:
Cursor cur = managedQuery(myPerson, null, null, null, null);

Android: 從Content Resolver取得Media (I)

底下節自Android developer並翻譯,
Media player可以詢問 ContentResolver來取得media file

ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do {
long thisId = cursor.getLong(idColumn);
String thisTitle = cursor.getString(titleColumn);
// ...process entry...
} while (cursor.moveToNext());
}
那如何使用呢?請看底下程式碼:

2011年9月26日

MyCuber (for Rubik Cube) 我的魔方

Available in Android Market
MyCuber @ Android Market

 MyCuber (Rubik cube3x3)
    • 依據世界方塊協會World Cube Association比賽規則設計模擬比賽情境計時,加上獨特的語音讀秒功能,讓使用者在解魔術方塊的同時,也能得知各階段所花費的時間,以利針對弱點加強練習,另外也可以針對先前解過的亂轉序列,重新再試一次。
    • 針對推廣魔術方塊運動而言,可以取代昂貴的計時裝置,提供方便又有效的計時紀錄工具
    • 畫面配色簡捷強調字幕的數字方便閱讀      

     剛出爐熱騰騰的軟體還在冒煙zZZ..搞了整個晚上終於成功上架了,原來還要等一陣子才會出現在市集,我真是太心急了點,連忙Google了大半夜想搞清楚是哪裡出錯(愛用網路Google的通病:-),百思不解結果休息一會兒就自動OK了,真是天下本無事,庸人自擾之。

2011年9月21日

連結: Android Shapes – Example » Developer Papercuts

Android Shapes – Example » Developer Papercuts:

漸層底圖效果

Android: 使用資源Resource中的顏色和字串

首先在/res/values/目錄底下產生一個xml檔
<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<string name="title">MyCuber</string>
<color  name=”backcolor”>#006fff</color>
</resources>

Android: 網路是否通?

記得在AndroidManifest.xml加上
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
public boolean isNetworkAvailable() {
 ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo networkInfo = cm.getActiveNetworkInfo();
  // if no network is available networkInfo will be null, otherwise check if we are connected
  if (networkInfo != null && networkInfo.isConnected())
        return true;
  return false;
}

Android: 免費圖示icon


http://commons.wikimedia.org/wiki/Crystal_Clear
http://www.famfamfam.com
http://iconlet.com
http://www.iconfinder.net/browse

2011年9月20日

小米手机: 值得期待!

小米手机官网:
應該是便宜(1999元人民幣)又好的手機,對大陸手機越來越有好感。目前手上的是華為的ideos手機,用起來中規中矩的。

处理器高通双核 MSM8260 1.5GHz
网络 GSM/WCDMA
RAM 1GB DDR2 RAM
ROM 4GB
图形处理器Adreno 220
屏幕夏普4寸854*480像素 TFT(半反半透)
相机800万像素、2.4最大光圈、自动对焦+LED
操作系统MIUI—深度定制的Android系统(開放刷機)
机身尺寸125*63*11.9mm
重量149g
电池1930mAh


2011年9月19日

蘇三起解...

還記得小時候 (嗯,是很小很小的時候 : )
聽姊姊唱這段京劇,只覺得此人好慘呀,覺得心中難過,卻又說不上來。
現在我明白了...
一位弱女子在腐敗官僚的嚴刑逼迫下,她的慘只能往心裡忍,也想認命算了,
但心裡最終還是捨不下那日思夜盼的情郎。
那哀怨泣訴無助,願來世作犬馬報答,她是多麼想念他呀,真是令人憐惜不忍。
現在拜網路之賜,可以聽到並看到各種版本的表演,真是Good Go !
唱詞如下:
蘇三離了洪桐縣,將身來在大街前,未曾開言我心內慘,過往的君子聽我言。
哪一位去往南京轉,與我那三郎把信傳。就說蘇三把命斷,來生變犬馬我當報還。
經典版的
底下有年輕版和幼兒版的更是棒...

連結: 臺北市政府公開資料平台

臺北市政府公開資料平台:
底下引自上述網址

data.taipei臺北市政府公開資料平台
臺北市政府為推動開放政府(Open Government)之資料公開政策,整合本府公開資料於單一入口網站以供大眾利用。目前資料目錄包含約130項以上資料集,不僅格式多元且隨時更新,另為提供更佳服務品質,新資料集將持續加入。
我們的目標:
  • 提供政府公開資料更簡易的取得管道
    將資料查詢及使用說明集中於單一入口,以提升資訊服務品質。
  • 提倡政府公開資料加值及應用
    鼓勵個人、企業和組織運用政府公開資料創造知識資產及便民服務,提昇臺北城市友善度。
  • 提高政府施政透明度及效能
    以服務、資料集、統計數據等形式公開資料,營造民眾參與協同合作的資訊基礎環境。

2011年9月17日

連結: OpenCV v2.3 for Android

Using Android binary package with Eclipse — OpenCV v2.3 documentation:

2011年9月11日

Android: OpenGL ES 1.0 範例

OpenGL ES Tutorial for Android – Part I – Setting up the view
Yet Another Tutorial on Android 3D Graphics using OpenGL ES Including Nehe's Port:

Android從1.0開始,就支援Open Graphics Library (OpenGL)移動裝置版 OpenGL ES API 用來進行硬體加速2D和3D圖形處理。從Android 2.2 (API Level 8)開始支援OpenGL ES 2.0 API規格(和J2ME JSR239 OpenGL ES API類似)有兩個基本Class讓你方便使用OpenGL ES API。

GLSurfaceView
  • 類似SurfaceView,像畫布一樣在上面作畫,若想接收觸控訊息時,就實做個touch listener,見範例TouchRotateActivity。@Override public boolean onTouchEvent(MotionEvent e) { ........}
GLSurfaceView.Renderer
     此界面實現了在GLSurface上畫畫的動作,經由setRenderer()設定,必須實現方法:
  • onSurfaceCreated(): 當產生GLSurface時呼叫一次。在這裡執行設定OpenGL環境變數,起始  OpenGL圖形物件等動作。 
  • onDrawFrame(): 每一次GLSurface重畫時呼叫此函數。 
  • onSurfaceChanged(): 當GLSurface改變時呼叫此函數,包含大小、方向等。

2011年9月10日

2011/6/25 Feliks Zemdegs 魔術方塊世界紀錄 5.66 秒

他又破了自己的世界紀錄,真是厲害,用的據說是大雁展翅喔!
5.66秒只夠我愣一下 :)
(2011年6月25日的澳大利亞墨爾本2011冬季公開賽,澳洲Feliks Zemdegs)
底下是慢動作
慢動作
看起來他的作法,基本上是CFOP,但似乎十字和F2L同時做了。
白面在上或黃面在上,看哪一面較容易!
更多教學影片

Android : 應用程式的唯一ID

Android Developers Blog: Identifying App Installations:
該文章建議使用UUID來作註冊號碼,若要與機器相關且唯一,則Android v2.3 版之後可用底下的ANDROID_ID,但之前的v2.2版會抓到同一個數字9774d56d682e549c !!
String android_id =  Settings.Secure.getString(getContentResolver(),        android.provider.Settings.Secure.ANDROID_ID);

本以為呼叫 getLine1Number()就可輕鬆得知手機號碼,實測之後發現只有一片古老的中華電信sim卡,可以抓到手機號碼。上網google一下,才發現手機號碼可能不會存在sim卡中。

2011年9月9日

Android 畫圖表工具: achartengine

achartengine - Charting library for Android - Google Project Hosting: "AChartEngine is a charting library for Android applications. It currently supports the following chart types:

line chart
area chart
scatter chart
time chart
bar chart
pie chart
bubble chart
doughnut chart
range (high-low) bar chart
dial chart / gauge
combined (any combination of line, cubic line, scatter, bar, range bar, bubble) chart
cubic line chart
All the above supported chart types can contain multiple series, can be displayed with the X axis horizontally (default) or vertically and support many other custom features. The charts can be built as a view that can be added to a view group or as an intent, such as it can be used to start an activity.
AChartEngine is currently at the 0.7.0 release. New chart types will be added in the following releases. Please keep sending your feedback such as we can continually improve this library.

Find us on Facebook, too: http://www.facebook.com/achartengine

"

'via Blog this'

2011年9月8日

連結: 使用 ZXing 產生QR碼


条形码/二维码之开源利器ZXing图文介绍 - Michael - ITeye技术网站:
条码扫描二维码扫描——ZXing android 源码简化 - NewObject - 博客园:


遇到有關JAVA的東東,還是不如浸淫許久的高手,一語就可以點破。
還好有各路高手無私的發文,看來JAVA像是Android的內功心法,必須扎實地KK。


連結: How to create and save a screenshot from a SurfaceView on Android Development

How to create and save a screenshot from a SurfaceView on Android Development:

Android: ZXing 使用Intent進行QR碼掃描

Simple access to barcode scanning in Android, via Intents:
ZXing 掃描QR條碼的程式庫

使用Intent呼叫ZXing來掃描QR碼
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);

接收掃描後結果
public void onActivityResult(int requestCode,int resultCode,Intent it) {
  if (requestCode == 0) {
     if (resultCode == RESULT_OK) {
        String contents = it.getStringExtra("SCAN_RESULT");
        String format = it.getStringExtra("SCAN_RESULT_FORMAT");
       // Handle successful scan
     } else if (resultCode == RESULT_CANCELED) {
      // Handle cancel
     }
  }
}

2011年9月6日

Android: 抓取Webview載入網頁的HTML碼

(出處)lexanderA » Extracting HTML from a WebView:

藉著setWebViewClient設定,當WebView載入網頁後onPageFinished,巧妙地插入JavaScript碼。利用JavaScript的document.getElementsByTagName傳出網頁的HTML原始碼,然後呼叫我們經由addJavascriptInterface掛上的showHTML函數,HTML碼就手到擒來了!

mWebView = (WebView) findViewById(R.id.webview);
WebSettings ws = mWebView.getSettings();
ws.setSavePassword(false);
ws.setSaveFormData(false);
ws.setJavaScriptEnabled(true);
ws.setSupportZoom(false);

mWebView.setWebChromeClient(new MyWebChromeClient());
mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"HTMLOUT");
mWebView.setWebViewClient(new WebViewClient(){ 
    @Override 
    public void onPageFinished(WebView view, String url)  { 
      mWebView.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+
     document.getElementsByTagName('html')[0].innerHTML+'</head>');"); 
   } 
}); 

底下就是用AlertDialog顯示網頁上的html碼。

2011年9月5日

轉錄:如何把InputStream變成字串?

(出處: www.kodejava.org)
Learn Java by Examples - How do I convert InputStream to String?:

public String convertStream2String(InputStream is) throws IOException{
 if (is != null) {
   Writer writer = new StringWriter();
   char[] buffer = new char[1024];
   try {
     Reader rr=new BufferedReader(new InputStreamReader(is,"UTF-8"));
     int n;
     while ((n = rr.read(buffer)) != -1) 
             writer.write(buffer, 0, n);
   }finally {
     is.close();
   }
   return writer.toString();
 }else 
  return "";
}

2011年9月3日

TelephonyManager | Android Developers

TelephonyManager | Android Developers:

TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
int sim_state = tm.getSimState();

SIM卡的狀態:
int SIM_STATE_UNKNOWN=0                   SIM card state: Unknown."
int SIM_STATE_ABSENT=1                         SIM card state: no SIM card is available in the device
int SIM_STATE_PIN_REQUIRED=2            SIM card state: Locked: requires the user's SIM PIN to unlock
int SIM_STATE_PUK_REQUIRED=3          SIM card state: Locked: requires the user's SIM PUK to unlock
int SIM_STATE_NETWORK_LOCKED=4 SIM card state: Locked: requries a network PIN to unlock
int SIM_STATE_READY=5                          SIM card state: Ready

連結:Managing Android Resources

by Mike Guidry
Android best practices suggest that functionality and the resources supporting that functionality should be as separated as possible. This is typically accomplished by accessing resources when needed within the Java code from external files. Therefore, we need a systematic way to access resources from XML files and from Java code. This appendix outlines the most important issues associated with that management.

連結:APK Piracy: Using private code & resources in Android


by jo.se/f pfleger
Did you know that the Android SDK makes it relatively easy to load code and resources from other apks into your own application? One way is to use a PathClassLoader and point it to an arbitrary APK:
new PathClassLoader("/system/app/Mms.apk", getClassLoader());
Another way is to use createPackageContext and use that context's ClassLoader to instantiate objects and load referenced resources.
( 閱讀全文... ):

連結:Android App Development: Menus Part 3: Alternative Menus | Mobile Orchard

Android App Development: Menus Part 3: Alternative Menus | Mobile Orchard:

by MINA SAMY on 16. MAR, 2011 in ANDROID, TUTORIALS

Android提供Alternative menus,它讓應用程式之間可以互相幫助。此種選項可以指向另一支程式,透過Intent讓它處理此特殊資料型別的物件。
.....

2011年8月30日

連結:Android Developer Guide

Android Developer Guide:
from Linuxpia
仔細的介紹!

2011年8月27日

Android: doom-android - port doom to android phone

doom-android - port doom to android phone - Google Project Hosting

Android: android rtmp network recorder

android-recorder - android rtmp network recorder - Google Project Hosting

This is a complete example for android-rtmp-client. Now you can download the whole project from Downloads tab.
android-recorder是为演示android-rtmp-client库在android上的使用而创建的项目,这只是一个功能演示,而不是一个完整的产品。每一次迭代过程中的代码和相关工具都已打包上传到 Downloads下。
Main change of each version:
Get PCM data from mic.
Encode with speex.

Android: Tutorial

Android Tutorial

10 Open Source Android Apps which every Android developer must look into

10 Open Source Android Apps which every Android developer must look into

讓Blogger支援Syntax Highlighting

想顯示程式的Syntax Highlighting,在網上google半天,先找到SyntaxHighlighter。用了之後效果是很棒,但因為連結它所提供的網站速度,還是有點兒慢,所以今天繼續找尋別的方式。結果踏破鐵鞋無覓處,得來全不費功夫,Google的google-code-prettify就很好用了呀!真奇怪,Blogger也是Google的,怎麼不內建此功能呢?

參考網站說明和作法整理如下:將底下的javascrip放到範本</head>之前即可,其中修改了背景顏色、邊框顏色和邊距等參數。
<script language='javascript' src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>
<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/>
<style>
pre {
  background-color : #f7f7f7;
  overflow         : auto ;
}
pre.prettyprint { padding: 12px; border: 1px solid #777; }
</style>

Android HttpClient / Java URL

取得網頁

String urL = "http://www.網址..";
HttpPost  httpP = new HttpPost (urL);
List <NameValuePair> params = new ArrayList <NameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
try {
    httpP.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
    HttpResponse httpR = new DefaultHttpClient().execute(httpP);
    if (httpR.getStatusLine().getStatusCode() == 200) {
    String ret = EntityUtils.toString(httpR.getEntity());
    Toast.makeText(main.this, out1, Toast.LENGTH_LONG).show();
    }
} catch (Exception e) {
  e.printStackTrace();
}

取得圖片
try {
    String urlAddress = "http://a.rimg.com.tw/ahd/01_106.jpg" ;
    InputStream is = (InputStream) (new URL(urlAddress)).getContent();
    Drawable image = Drawable.createFromStream(is, "src");
    capImage.setImageDrawable(image);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

2011年8月26日

Android: Bluetooth相關

BluetoothChat - Bluetooth Chat | Android Developers

JWorld@TW Java論壇 - Android Bluetooth API 使用心得筆記

apps-for-android - Sample Applications for the Android platform - Google Project Hosting

anddev.org • View topic - Serial over Bluetooth simple test client.

2011年8月25日

轉貼:Android TTS学习——TTS初体验 - ichliebephone的专栏 - 博客频道 - CSDN.NET

Android TTS学习——TTS初体验 - ichliebephone的专栏 - 博客频道 - CSDN.NET:
"ichliebephone的专栏"


Java : ==

== 運算在Java中被用來比較左右兩個名稱,是否指向同一物件,例如:
String a = new String("abcd");
String b = new String("abcd");
此時if (a==b)為false,因為a與b是分別指向不同的字串物件,

當要比較兩個字串內容是否相同,要用equals()
例如:

String a = new String("abcd");
String b = new String("abcd");


此時 if (a.equals(b)) 為true

2011年8月24日

Android: 存放檔案到sd卡


Activity的openFileOutput()將檔案存在手機內存記憶空間,
一般而言手機的內存記憶空間不大,存放小檔案還ok,
對於大檔案我們需放在外部的SD卡。
在AndroidManifest.xml中加入以下權限:  
      
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>       
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
            // 判斷手機是否已装有SD卡,且可以讀寫。  
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
                // 取得SD卡目錄
                File sdDir = Environment.getExternalStorageDirectory(); 
                File saveFile = new File(sdDir, "test.txt");  
                FileOutputStream outS = new FileOutputStream(saveFile);  
                outS.write("Hellow,World.許功閱".getBytes());  
                outS.close();  
            }

Android: 時鐘Clock機制

大略翻譯Android技術文件如下:
Android 有三種不同的時鐘可用,分別陳述如下:
  • System.currentTimeMillis() 如同掛在牆壁上的時鐘(時間/日期)以milliseconds表示之,可被使用者或經由網路隨意往前或往後調整的時鐘(函數setCurrentTimeMillis(long))。此時鐘應該只用來與真實時間相關是務上,例如行事曆或鬧鐘等應用程式。計算時距或經過時間,應該使用底下的時鐘。當使用System.currentTimeMillis() 時,可以接收 ACTION_TIME_TICKACTION_TIME_CHANGEDACTION_TIMEZONE_CHANGEDIntent的廣播來得知時間的改變。
  • SystemClock.uptimeMillis() 計算從系統啟動booted到現在所經過的milliseconds時間,但當系統進入深睡時(CPU停止,螢幕關閉,裝置等待外部輸入) 此時鐘會停止,除此之外不受其他影響。此時鐘是大部份計算時間間隔的基礎,例如Thread.sleep(millls)Object.wait(millis)System.nanoTime()
    它保證是遞增的,建議用來
    計算一般使用者介面事件、效能或其他任何無須考慮裝置睡覺時間的時間間隔。uptimeMillis() clock 傳回 timestamp 值。
  • SystemClock.elapsedRealtime() 計算從系統啟動booted到現在所經過的milliseconds時間,包括系統深睡時間。此時鐘用來必須計算橫跨多個系統睡覺時間的時間間隔。

Android: AlarmManager 鬧鐘用法


Alarm Manager元件用來排程,當時間到時系統會廣播註冊指定的Intent啟動目標程式,就算目標程式並未在執行中也一樣。若是裝置在睡眠中,則依參數而定,註冊的鬧鐘會保留或喚醒裝置。當系統關閉並rebooted時,會清除鬧鐘的設定。當廣播接受端執行onReceive() 時,Alarm Manager會保持CPU清醒直到處理結束。裝置有可能一旦執行完onReceive()時,立刻進入昏睡(睡眠不足:),所以不要在onReceive()中呼叫非同步動作的函數。若一定要作時,請自行處理wake lock policy(鎖定清醒)。
  • ELAPSED_REALTIME 使用 elapsedRealtime() 計時;從系統啟動後至目前的時間(包含睡覺時間)
  • ELAPSED_REALTIME_WAKEUP 同上,並喚醒裝置
  • RTC 使用 currentTimeMillis() 牆壁時鐘UTC格式
  • RTC_WAKEUP  同上,並喚醒裝置

2011年8月23日

Android: Intent 呼叫瀏覽器開啟指定網頁

底下試舉兩種Intent呼叫方法,用兩個Button掛在同一個接收器用getID()區分。
Button.OnClickListener btnCallTestClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
    try {
        String strURL1 = "http://tw.yahoo.com";
        String strURL2 = "http://www.google.com.tw";
        switch (arg0.getId()) {
         case R.id.callTest1:
          Intent ie = new Intent(Intent.ACTION_VIEW,Uri.parse(strURL1));
          startActivity(ie);
          break;
         case R.id.callTest2:
          Intent ie2 = new Intent();
          ComponentName comp = new ComponentName("com.android.browser",
            "com.android.browser.BrowserActivity");
          ie2.setComponent(comp);
          ie2.setAction(Intent.ACTION_VIEW);
          ie2.setData(Uri.parse(strURL2));
          startActivity(ie2);
          break;
        }
        //
     } catch (Exception e) {
        e.printStackTrace();
     }
       
}};

連結: 在 Android 裡讓鬧鐘設定撐過關機(AlarmManager)

Java Artisan: 在 Android 裡讓鬧鐘 Alarm設定撐過關機(AlarmManager)

2011年6月15日

使用內部儲存空間

你可以直接存放檔案在裝置的內部儲存空間,預設存放在內部儲存空間的檔案只有你的程式可以存取。當使用者移除你的程式時,這些檔案也會一併被移除。

寫出檔案
呼叫openFileOutput()傳入檔名和操作模式。傳回一個FileOutputStream。
String FILENAME = "hello_file";
String string = "hello world!";
 
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
MODE_PRIVATE產生或覆蓋檔案,私有
MODE_APPEND增添檔案
MODE_WORLD_READABLE外界可讀取
MODE_WORLD_WRITEABLE外界可寫入

讀取檔案
呼叫openFileInput()傳入檔名,傳回一個FileInputStream。
也可以讀取存放在 res/raw/目錄中的檔案,呼叫openRawResource(),傳入 R.raw. ,傳回一個InputStream(只能讀取無法寫入)。

其他相關函數
getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.

RadioButton用法

In AndroidManifest.xml宣告如下:
        ....
        <RadioGroup 
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:checkedButton="@+id/horizontalRB"
            android:gravity="center_horizontal"
        >
          <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:text="@string/hor"
            android:textColor="@color/black"
            android:id="@id/horizontalRB"          />
          <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:textColor="@color/black"
            android:text="@string/ver"
            android:id="@+id/verticalRB"          />
        RadioGroup>
         ...
在java程式中取值,用Intent帶值putExtra呼叫其他Activity。
        RadioButton rb1=(RadioButton)findViewById(R.id.horizontalRB);
        RadioButton rb2=(RadioButton)findViewById(R.id.verticalRB);        
 
        Intent intent = new Intent();
        if (rb2.isChecked())
            intent.putExtra("vertical",true);
        else
            intent.putExtra("vertical",false);
 
        intent.setClass(getBaseContext(), main.class);
        startActivity(intent);