顯示具有 Android基礎知識 標籤的文章。 顯示所有文章
顯示具有 Android基礎知識 標籤的文章。 顯示所有文章

2011年4月21日 星期四

Notification

Notification
簡易範例
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
     
    Notification notification = new Notification();
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    mNotificationManager.notify(123, notification);

2011年4月11日 星期一

SharedPreferences物件


SharedPreferences物件
偏好設定SharedPreferences可用來紀錄資料
在Activity重新啟動後,可回復關閉前資訊 
通常在"onPasue"寫入參數,在"onRseume"讀取參數

寫入參數
    SharedPreferences settings = getSharedPreferences ("DATA", 0);
    SharedPreferences.Editor PE = settings.edit();
    PE.putString("data_str", "hello");
    PE.putInt("date_int", 100);
    PE.commit();


    or

    SharedPreferences settings = getSharedPreferences ("DATA", 0);
    settings.edit()
        .putString("data_str", "hello");
        .putInt("date_int", 100);
        .commit();

讀取參數
    SharedPreferences settings = getSharedPreferences("DATA", 0);
    // 如果讀不到值,就會回傳後面設定的參數
    String str = settings.getString("data_str", "null");
    int i = settings.getInt("date_int", 0);

2011年4月8日 星期五

BroadcastReceiver物件

BroadcastReceiver物件
有部分資訊,會經由Android系統透過廣播的方式傳送給應用程式或服務。
而BroadcastReceiver就是用來接收這一類訊息的物件

    // 加入filter,選擇要receiver的對象
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(mBroadcastReceiver, filter);

    // BroadcastReceive(以電池為例)
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                switch (intent.getIntExtra("status", 0)) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    bat_status = "unknown";
                    break;
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    bat_status = "charge";
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    bat_status = "discharge";
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    bat_status = "not_charge";
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    bat_status = "full";
                    break;
                }
   
                bat_level = intent.getIntExtra("level", 0);
            }
        }
    };

    // close when leaving
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

2011年4月6日 星期三

Service類別

Service類別
Service沒有提供與用戶進行互動的展示層,為一背景執行的程式,一般來說,若是不需要UI操作的程序則可使用Service來完成。

Service一般是由Activity或Context物件來啟動,啟動的方式分為二種:
    透過startService()啟動:啟動後直到Service呼叫自身的stopSelf或stopService時才停止
    透過bindService()啟動:當綁定的Context被銷毀時,停止執行

生命週期如下所示:
程式碼
    public class ExampleService extends Service {
        int mStartMode;       // indicates how to behave if the service is killed
       
IBinder mBinder;      // interface for clients that bind
       
boolean mAllowRebind; // indicates whether onRebind should be used

        public void onCreate() {
           
// The service is being created
       
}
       
public int onStartCommand(Intent intent, int flags, int startId) {
           
// The service is starting, due to a call to startService()
           
return mStartMode;
       
}
        public IBinder onBind(Intent intent) {
           
// A client is binding to the service with bindService()
           
return mBinder;
       
}
       
public boolean onUnbind(Intent intent) {
           
// All clients have unbound with unbindService()
           
return mAllowRebind;
       
}
        public void onRebind(Intent intent) {
           
// A client is binding to the service with bindService(),
           
// after onUnbind() has already been called
       
}
       
public void onDestroy() {
           
// The service is no longer used and is being destroyed
       
}
    }

Intent & Bundle物件

Intent & Bundle物件

Intent
用於應用程式之間的通訊,例如說從一個Activity要呼叫其他的Activity(Server...)

程式碼
    Intent intent = new Intent(Test.this, Test2.class);
    startActivity(intent);
    startService(intent);

另外Intent裡也可以放入"動作"屬性
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
    startActivity
(intent);

若是需要回傳值的時候可以使用"startActivityForResult()"的方法,如下
    private void pickContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
        startActivityForResult
(intent, PICK_CONTACT_REQUEST);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
    
        // coding the function which you want to do
       
}
    }


IntentFilter
當Intent元件之間在傳遞時,若需要告知Android系統自己能夠回應或處理哪些Intent,則可以使用IntentFilter物件。
IntentFilter可以過濾元件無法回應及處理的Intent,只將自己的Intent接收進來處理。
通常應用於Boradcast Receiver元件上。

PendingIntent
在Service裡無法使用startActivity()這種方法,這時候就可以使用PendingIntent這個物件

程式碼
    Intent intent = new Intent(this,Test.class);
    PendingIntent pending =
        PendingIntent.getActivity(
            this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        pending.send();
    } catch (CanceledException e) {
        e.printStackTrace();
    }

Bundle
用來傳送不同程序間的資料,通常與Intent一起使用

程式碼
    Test.java
    Intent intent = new Intent(this,Test.class);
    Bundle bundle = new Bundle();
    bundle.putInt("brightness", value);
    intent.putExtras(bundle);

    Test2.java
    Bundle bundle = this.getIntent().getExtras();
    int value = bundle.getInt("brightness");

Activity類別

Activity類別

Activity是Android裡最常見的一種元件,可將每一個Activity看成一個螢幕,為使用者提供進行互動的可視介面,應用程式可根據需求包含一個或多個Activity,這些Activity一般都是繼承自android.app套件下的Activity類別,而Activity之間的執行是互相獨立的。

Activity的生命週期如下圖所示:
主要分成六個部分:
    onCreate():Activity啟動時執行,通常用來初始化變數及設定Layout
    onStart():Create完之後會到這邊,執行Activity啟動後要執行的動作
    onResume():暫停之後,重新啟動
    onPause():暫停,當不是在最上層顯示時,會執行此程序
    onStop():停止,當程序很久沒有被呼叫時觸發
    onDestroy():銷毀,Activity離開時執行

程式碼:
    public class Test extends Activity {
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.test);
        }
        protected void onStart() {
           
super.onStart();
        }
        protected void onResume() {
           
super.onResume();
        }
        protected void onPause() {
           
super.onPause();
        }
        protected void onStop() {
           
super.onStop();
        }
        protected void onDestroy() {
            super.onDestroy();
        }
    }

一般除了onCreate()以外,其他的都用protected宣告,避免外部其他人使用,造成問題