2011年9月8日

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_TICK,ACTION_TIME_CHANGED 和ACTION_TIMEZONE_CHANGED等Intent的廣播來得知時間的改變。
  • 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);