2010年10月20日 星期三

Android Resources 資源檔-使用(三)

resourceID的值由兩個部份組成type(如string)與name(如hello)
取得Resource的方式
一.在Java Code中使用resource
1.取得resourceID的語法為
package_name.R.resource_type.resource_name
若在自己專案內package_name可以不用寫
例
R.string.hello
android.R.color.secondary_text_dark
2.取得Resource Class
利用 Context.getResources()取得Resource Class
再利用Resource提供的各項method來取得各類型的resource
3.範例
例1:
Resources res=Context.getResources();
String str=res.getString(R.string.hello)
例2:
TextView.setText(rsid:int)就可直接使用,用自己找出resources
例3:
imageView.setImageResource(R.drawable.myimage);
二.在XML中使用resource
1.取得resourceID的語法為
@package_name:resource_type/resource_name
如果是在自己專案內的resource就不用寫package_name
在tag內將resourceID指定給tag,tag即會利用resourceID取得資源
2.使用sttle的語法為
?package_name:resource_type/resource_name

2.範例
例1:
 <?xml version="1.0" encoding="utf-8"?>  
 <EditText xmlns:android="http://schemas.android.com/apk/res/android"  
      android:layout_width="fill_parent"  
      android:layout_height="fill_parent"  
      android:textColor="@android:color/secondary_text_dark"  
      android:text="@string/hello" />       
以上範例,textColor用到android內建的資源,所以用@android:color/secondary_text_dark
而text用到是自己專案內的資源,所以用@string/hello
例2:
 <EditText id="text"  
           android:layout_width="fill_parent"  
           android:layout_height="wrap_content"  
           android:textColor="?android:textColorSecondary"  
           android:text="@string/hello_world" />       

三.使用系統內建resource
若要使用系統預設的resource,可用android.R取得
注意:R是本身專案的resource檔案,而android.R是系統提供的預設resource檔


四.執行過程中的異動
當使用者的Device在使用過程中做了變動,譬如說,旋轉或改變語系,系統會因為這樣的改變而將正在進行的Activity進行onDestroy(),然後進行onCreate()重新顯示以套用新的改變。
而在進行onDestroy()前會進行資料儲存動作,好讓重新建立後可以回復資料,其流程如下
onSaveInstanceState()->onDestroy()->onCreate()->onRestoreInstanceState()
其執行方式有以下兩種方式,各有優缺點
1.保留資訊,自動重新啟動
當config改變發生時,允許Activity在自動restart,並把狀態資料帶到Activity新的instance上,若要重新建立新的instance,如果資料來源是來自網路,可能會因為重新建立連線而發生更久的時間。
通常用來儲存狀態用的都是bundle物件,但bundle物件並不適合儲存大量資料(如點陣圖),所以在runtime時要保留資料會是用以下作法
1.Override onRetainNonConfigurationInstance()回傳你要儲存
  的物件,onRetainNonConfigurationInstance()會發生在
  onStop()與onDestroy()之間
2.當create後呼叫getLastNonConfigurationInstance()取回物件
例
儲存
@Override
public Object onRetainNonConfigurationInstance() {
    final MyDataObject data = collectMyLoadedData();
    return data;
}    
取回
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
    if (data == null) {
        data = loadMyData();
    }
    ...
}    
2.取得通知,自己手動處理改變的訊息
當config改變發生時,只發出相關通知,讓使用者自己決定是否要restart,為了效能考量,在部份config發生改變時,並不自動restart Activity,就需要使用者自己手動去處理外觀異動的部份,而無法享受到使用衍生res所帶來的方便
作法如下:
1.先在Manifest內設定Activity要監聽哪些事件變化
2.覆寫onConfigurationChanged(),當有config改變時,
  這裡會接收到新的config物件
例
manifest.xml
 <activity android:name=".MyActivity"  
       android:configChanges="orientation|keyboardHidden"  
       android:label="@string/app_name">  

Activity內
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
    }
}    

Android Resources 資源檔-Sample與使用範例(二)

一.anim/:XML檔案
定義所有的tween動畫
例:res/anim/hyperspace_jump.xml
 <set xmlns:android="http://schemas.android.com/apk/res/android"  
      android:shareInterpolator="false">  
      <scale  
           android:interpolator="@android:anim/accelerate_decelerate_interpolator"  
           android:fromXScale="1.0"   
           android:toXScale="1.4"   
           android:fromYScale="1.0"   
           android:toYScale="0.6"   
           android:pivotX="50%"  
           android:pivotY="50%"  
           android:fillAfter="false"  
           android:duration="700" />  
      <set  
           android:interpolator="@android:anim/accelerate_interpolator"  
           android:startOffset="700">  
           <scale  
                android:fromXScale="1.4"   
                android:toXScale="0.0"  
                android:fromYScale="0.6"  
                android:toYScale="0.0"   
                android:pivotX="50%"   
                android:pivotY="50%"   
                android:duration="400" />  
           <rotate  
                android:fromDegrees="0"   
                android:toDegrees="-45"  
                android:toYScale="0.0"   
                android:pivotX="50%"   
                android:pivotY="50%"  
                android:duration="400" />  
      </set>  
 </set>  
在Java內使用動畫
ImageView image = (ImageView) findViewById(R.id.image);
Animation hyperspaceJump = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
image.startAnimation(hyperspaceJump);

二.color/:XML檔案
定義colors state list,也就是以一個物件的方式設定在各種狀態時的color變化,如button會有各種state的color變化,可將這樣的color state設定成xml
例:res/color/button_text.xml:
 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
      <item android:state_pressed="true"  
            android:color="#ffff0000"/> <!-- pressed -->  
      <item android:state_focused="true"  
            android:color="#ff0000ff"/> <!-- focused -->  
      <item android:color="#ff000000"/> <!-- default -->  
 </selector>  
在XML Layout上套用到Button上
 <Button  
 android:layout_width="fill_parent"  
 android:layout_height="wrap_content"  
 android:text="@string/button_text"  
 android:textColor="@color/button_text" />  

三.drawable/:bitmap檔案
包括(.png .9.png .jpg .gif),或透過XML檔案所描述的圖形,
如State lists,Color drawables,Shapes

四.layout/:XML檔案
定義使用者使用介面的layout,每一個Layout會相當於我們看到的一個page

五.menu/:XML檔案
定義該App的menu,例如Options Menu, Context Menu, or Sub Menu
例:res/menu/example_menu.xml:
 <menu xmlns:android="http://schemas.android.com/apk/res/android">  
      <item android:id="@+id/item1"  
            android:title="@string/item1"  
            android:icon="@drawable/group_item1_icon" />  
      <group android:id="@+id/group">  
           <item android:id="@+id/group_item1"  
                 android:title="@string/group_item1"  
                 android:icon="@drawable/group_item1_icon" />  
           <item android:id="@+id/group_item2"  
                 android:title="G@string/group_item2"  
                 android:icon="@drawable/group_item2_icon" />  
      </group>  
      <item android:id="@+id/submenu"  
            android:title="@string/submenu_title" >  
           <menu>  
                <item android:id="@+id/submenu_item1"  
                      android:title="@string/submenu_item1" />  
           </menu>  
      </item>  
 </menu>  
在Activity的Java內使用
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.example_menu, menu);
  return true;
}

六.raw/:任意檔案用他原本的資料格式儲存
系統不會對檔案做壓縮處理,要開啟這些檔案的InputStream,要透過Resources.openRawResource()呼叫該resourceID(R.raw.filename)取得,若是希望透過原始檔名來取得檔案,建議可以把檔案存在/assets/目錄下
在/assets/目錄下的檔案是沒有resourceID的,都是透過AssetManager來存取

七.values/:XML檔案
包含一些簡單的值設定,如string,color,style,通常會把同類型的寫在一個檔案內
1.arrays.xml
例
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
      <array name="icons">  
           <item>@drawable/home</item>  
           <item>@drawable/settings</item>  
           <item>@drawable/logout</item>  
      </array>  
      <array name="colors">  
           <item>#FFFF0000</item>  
           <item>#FF00FF00</item>  
           <item>#FF0000FF</item>  
      </array>  
 </resources>  

JAVA使用
Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);
TypedArray colors = res.obtainTypedArray(R.array.icons);
int color = colors.getColor(0,0);
2.colors.xml
例
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
   <color name="opaque_red">#f00</color>  
   <color name="translucent_red">#80ff0000</color>  
 </resources>  

JAVA使用
Resources res = getResources();
int color = res.getColor(R.color.opaque_red);

XML使用
 <TextView  
 android:layout_width="fill_parent"  
 android:layout_height="wrap_content"  
 android:textColor="@color/translucent_red"  
 android:text="Hello"/>  
3.dimens.xml
例
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
      <dimen name="textview_height">25dp</dimen>  
      <dimen name="textview_width">150dp</dimen>  
      <dimen name="ball_radius">30dp</dimen>  
      <dimen name="font_size">16sp</dimen>  
 </resources>  

Java使用
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);

XML使用
 <TextView  
 android:layout_height="@dimen/textview_height"  
 android:layout_width="@dimen/textview_width"  
 android:textSize="@dimen/sixteen_sp"/>  
4.string.xml
例
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
      <string name="hello">Hello!</string>  
 </resources>  

JAVA使用
String string = getString(R.string.hello);

XML使用
 <TextView  
 android:layout_width="fill_parent"  
 android:layout_height="wrap_content"  
 android:text="@string/hello" />  
5.style.xml
例
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
      <style name="CustomText" parent="@style/Text">  
           <item name="android:textSize">20sp</item>  
           <item name="android:textColor">#008</item>  
      </style>  
 </resources>  

XML使用
 <?xml version="1.0" encoding="utf-8"?>  
 <EditText  
      style="@style/CustomText"  
      android:layout_width="fill_parent"  
      android:layout_height="wrap_content"  
      android:text="Hello, World!" />  

八.xml/:任何其他的xml檔案放在這目錄
以Resource.getXML()讀取,各式的XML設定檔config都放在這目錄下

Android Resources 資源檔-基本概念(一)

一.說明
在Android下會需要用到的各種資源都會放在res/目錄下,包括版面,圖片,文字字串,資料陣列,顏色...等各式實體內容都會放在這目錄下,而在res/下主要了包含以下8個目錄,分別代表8種不同類型的resource
1.anim/:XML檔案,ㄐ定義所有的tween動畫
2.color/:XML檔案,定義colors state list,也就是以一個物件的
  方式設定在各種狀態時的color變化
3.drawable/:bitmap檔案,包括(.png .9.png .jpg .gif)
4.layout/:XML檔案,定義使用者使用介面的layout
5.menu/:XML檔案,定義該App的menu,例如Options Menu, Context Menu, or Sub Menu
6.raw/:任意檔案用他原本的資料格式儲存
7.values/:包含一些簡單的值設定,如string,color,style
8.xml/:任何其他的xml檔案放在這目錄

二.作業原理
在Android將整個專案Compile時,會將所有在res/目錄下的資源都會被Compile成一個R Class,而在res下的各種類型,則會成為R的subClass 如R.string R.drawable都是一個 class 。所以透過R Class可以讓你直接找到資源的resourceID,再利用resourceID來取到resource實體內容。無論資料內容是任何類型的資料,resourceID都只是個int值,而非實體資料內容,要取得實體內容,都需要依照要取得的resource類型,透過resourceID來取得
例如
在res/values/strings.xml內有一筆
 <string name='hello'>測試</string>  
因此R.string.hello即是這筆資料的resourceID,透過getString()才能取得真正的內容
String string = getString(R.string.hello);

三.R下SubClass
R下面的subclass,並非由各目錄的名稱或xml檔案名稱所訂,而是對應到資料類型。譬如說R.string這個次類別,string是來自於strings.xml內有tag,至於這tag所依附的xml檔名,是可以任意的設定(並非一定要設成strings.xml)
也可以把不同類型的資料放到同一個xml檔案內,只是通常會把相同資源放在同一個xml檔案內,方便管理

四.res下更多的衍生類別目錄
除了標準的八種類型目錄外,在res下可以看到更多的其他衍生出來的目錄。
譬如說有layout/ 也可看到layout-land/目錄,這些衍生出來的目錄,都是因應可以讓你開發的應用程式,可以因偵測到使用者device的條件不同,而提供有不同的使用介面與設定,包括解析度尺寸不同,或多語系,都可設定各自的顯視介面,這些目錄名稱的命名都是有規則的,在規則性的命名下,Android系統即會自動判斷要取用哪個目錄下的資源,來顯示在使用者的Device上

例如
在res/下除了有一個 layout/目錄提供標準的版面給使用者外,另外還有一個layout-land/目錄提供給橫向螢幕使用,也就是說當使用者以直式使用時,畫面上是以layout/目錄下的設定來顯示,當使用者把device轉向成橫式時,就會自動切換到以layout-land/目錄下的設定顯示

五.res衍生目錄命名規則
目錄名稱命名方式為resources_name-config_qualifier
resources_name:即原來資源類型的名稱,如string,color,array,...
config_qualifier:依照各類型資源各有不同的值可用
例如:
以Screen orientation螢幕方向來分,config_qualifier允許的值為port直,land橫
res/layout:一般標準layout
res/layout-land:針對橫向時用的layout

幾個常見的config_qualifier包括

1.Language:用來儲存依照不同語系地區所提供的resource
  例 值:en ,fr,tw,cn
  產生的目錄會是
  values-tw/
2.Screen size:螢幕解析度
  值:small,normal,large
3.Wider/taller screens:螢幕形狀,長形或一般
  值:long,notlong
4.Screen orientation:螢幕是直式或橫式
  值:port直,land橫
5.Dock mode:一般或車上模式 
可以用多個config_qualifier串接如 drawable-port-hdpi/,但順序需依照規格書內列表的順序描述

六.res衍生目錄需要用到重複資源的處理方式
當有一份resource(例如圖檔),要給多種設定檔使用,可以不用copy到每個folder各有一份,只需要建立Alias即可,並非所有resource都可提供Alias機制,如animation, menu, raw, 與其他在xml/ 目錄下的都不行
1.drawable 圖檔
例:如果有一張圖檔icon.png原本放在drawable目錄下,要給多個設定檔使用
但又不希望直接copy檔案到各目錄

1.將icon.png rename為 icon_oz.png(只要不是原檔名就好)
將檔案放到drawable/目錄下
2.產生一個icon.xml檔案
 <?xml version="1.0" encoding="utf-8"?>  
 <bitmap xmlns:android="http://schemas.android.com/apk/res/android"  
      android:src="@drawable/icon_oz" />  
放到各drawable-xxx/目錄下
3.使用上用
R.drawable.icon可取得
2.layout
例:有一份layout要提供多個設定檔使用
1.將原layout main.xml 改名為main_oz.xml
放到res/layout/
2.產生一個main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <merge>  
      <include layout="@layout/main_oz"/>  
 </merge>  
放到各目錄下
3.使用上
R.layout.main
3.string或其他
在要alias的項目填上對應資料即可
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
      <string name="hello">Hello</string>  
      <string name="hi">@string/hello</string>  
 </resources>  

2010年10月19日 星期二

Android基本概念

一.基本概念
Android Application是使用Java開發,compile成Java code,再利用Appt Tool將相關的resource包裝成apk檔,讓使用者可以下載安裝到他的device上,每個Application會以下列方式在系統執行。
1.每個App跑自己獨立的Linux Process,在不使用時關閉
2.每個Process有自己的VM,所以Ap是在一個完全隔離的環境下運作
3.預設每個App指定一個唯一的Linux user ID,App file只允許該
  App與該User使用,若要讓不同的App共用資料則要設定相同的
  User ID

二.元件
Android一個相當重要的特性是,每個App內包含了許多的元件,每個元件的功能都可以提供其他的App使用,你所開發的App想要使用其他App已經開發好的功能元件,不需要在程式內全部包進來或是去link它,也就是說系統會自行判斷,可以任何需要的時候去啟動任何Application的任何部份功能。

Android App並沒有一個單一的程式進入點(如main()),而是存在著以下四種元件,在必要時就實體化來使用執行
1.Activities
    每個Activity都繼承自Activity Class。
    Activity負責提供使用者介面讓使用者操作與互動。
    一個App可以包含一到多個Activity,在App起始時啟動,一個
    Activity,再由已開啟的Activity去開啟其他的Activity。
    每個Activity都會包含一個Window用來顯示畫面,預設window會
    填滿整個screen(手機),但window可以設定的更小或浮動在其他
    window上,例如popup window,window上所放的物件都是繼承自
    View Class,每個view都佔據著window內的一個矩形區塊,上層
    的view負責其子元素的layout安排,而最底層的child view則負
    責直接回應使用者的動作與輸入,利用Activity.setContentView()
    設定Activity最上層使用的View
    
2.Services
    Service提供一個可以在背景定時執行,無使用者介面的服務。
    譬如說在背景播放音樂,或是在internet上取得資料提供給
    Activity使用。    
    
3.Broadcast receivers
    繼承自BroadcastReceiver Class
    Broadcast receiver 是用來接收廣播的訊息並做回應,許多的
    廣播是來自於系統,譬如說時區改變、電池電力不足或使用者改
    變語系等,另外廣播也可來自於App的其他元件所發出來,例如
    App在下載完資料可以提供給其他App使用時,可以透過廣播讓其
    他App的Broadcast receiver可以接收到並使用
    
    Broadcast receiver沒有UI,但他可啟動Activity去顯示回應,
    或使用NotificationManager去提示使用者。
    Notification可以是device振動、或是閃爍...播放音效等可以
    吸引使用者注意,通常都會在螢幕上放一個icon,當Broadcast
    receiver接收到訊息要提示使用者,可以用NotificationManager
    讓icon有所變化    
    
4.Content providers
    繼承自ContentProvider
    Content provider提供可以讓其他App使用的data,data可以用
    file或sqlite形式儲存,提供讓其他App可以讀取與儲存資料的
    方法。App並不能直接呼叫ContentProvider的method,而是需要
    透過ContentResolver物件來呼叫ContentProvider。
    ContentResolver可以跟任何的ContentProvider做溝通,利用他
    來管理內部程序上的溝通

三.使用intent啟動元件
除了ContentProvider是透過ContentResolver來驅動使用外,其他三種元件的啟動都是透過Intent來啟動,一個intent物件是包含了要執行的內容資訊。對activities 與 services來說,intent包含了要執行的action與要用的data URI,譬如開啟圖片的連結位置等資訊,對Broadcast receiver來說,包含了要發布的action,例如當相機按鈕被按下時,將這按下按鈕的訊息發布給接收者

以下是各種元件的啟動方式
1.Activity
    透過傳遞intent物件給Context.startActivity()來啟動。接收
    到這intent的Activity,在Activity內可以透過getIntent()取
    得該intent資料。    
    一個Activity通常是由另一個Activity所觸發,如果在觸發的
    Activity後想要得到回傳資料,則改用
    Activity.startActivityForResult()來啟動Activity。
    例如要啟動另一個Activity讓使用者可以選取圖片,當使用者
    選好後,希望把選好的圖片回傳回來,回傳的資料會是用intent
    物件被回傳到原呼叫者的onActivityResult()內
2.Service
    透過傳遞intent到 Context.startService()內或是呼叫Service
    的onStart()來啟動Service。
    同樣的可以將intent傳給Context.bindService()在元件與Service
    間建立一個持續性的連線,當建立連線時,系統即會自動觸發
    Service內的onBind(),同時把intent物件丟給onBind(),若在呼
    叫onBind時,若還沒建立連線,則會自動呼叫bindService()建立,
    接下來就可以使用Service本身的method來用
3.Broadcast receiver
     透過傳遞intent到Context.sendBroadcast()、Context.sendOrderedBroadcast(),
     與Context.sendStickyBroadcast(),就可以把intent包好的訊息
     廣播出去,系統就會自動觸發有興趣的Broadcast receiver內部的
     onReceive(),同時onReceive()會接收到這個intent物件在做後續
     的處理程序    

四.關閉元件
ContentProvider只回應ContentResolver的需求,Broadcast receiver只在回應廣播時啟動,所以這兩種元件都不需要手動去關閉它,需要被關閉的元件只有Activity與Service。
1.Activity本身可透過finish()來關閉,而要關閉其他的Activity,
  例如利用startActivityForResult(),所啟動的Activity可以利用
  finishActivity()來關閉其他Activity
2.service本身可以透過stopSelf()關閉,或由外部透過
  Context.stopService()關閉,當元件已經不再被使用或當系統記
  憶體不足時會被強制關閉
五.manifest設定檔
一個Android程式包含了許多的元件還有resource檔案,在Android使用之前,需先確認資料的存在,每個App內都會有一個結構性的描述檔 AndroidManifest.xml,包含了包括activity,service,receiver,provider 等元素宣告,activity,service,provider若沒宣告在manifest檔案內,在系統內是無法使用的,只有receiver除了可以宣告在manifest內,也可以透過Context.registerReceiver()動態產生註冊到系統內

2010年10月1日 星期五

Air File實體檔案路徑

在開發AIR專案,如果需要利用File對使用者端做檔案存取
取得需要的實體檔案路徑,需要透過File的static變數來取得
以下是各變數所對應在Windows下的實體檔案位置

1.File.userDirectory:使用者目錄
C:\Documents and Settings\username

2.File.applicationDirectory:AIR APP執行檔所在路徑
D:\MyAirApp
3.File.applicationStorageDirectory:使用者本機可供該AIR應用程式,儲存資料的路徑
C:\Documents and Settings\username\Application Data\MyAirApp\Local Store

4.File.desktopDirectory:使用者桌面
C:\Documents and Settings\username\桌面

5.File.documentsDirectory:使用者我的文件資料夾
C:\Documents and Settings\username\My Documents