2011年3月3日 星期四

ActivityGroup中bindService的使用問題

一般的bindService:
private ServiceConnection serviceConnection = new ServiceConnection()
{
    public void onServiceConnected(ComponentName componentName,IBinder service)
    {
        // code
    }
    public void onServiceDisconnected(ComponentName componentName)
    {
        // code
    }
};

public void onCreate(Bundle savedInstanceState)
{
    ComponentName componentName = new ComponentName(this,test.class);
    Intent intent = new Intent();
    intent.setComponent(componentName);
    bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);
}
若此class為ActivityGroup中的child activity(如:tabhost)則會無法順利bindService
此時解決方法就是用getApplicationContext().bindService()取代bindService(),如下:
getApplicationContext().bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);

Explicit Intent

Explicit intent為明確指定欲切換目標的intent
基本上只要有設定intent的componentName就是Explicit intent
系統會選定componentName的內容做為切換intent的目標
而不去考慮其他的項目(像是action)


1. 設定componentName的內容
(1) 用於同一個package的intent :
ComponentName componentName = new ComponentName(this, TestActivity.class); // 不用指定package
(2) 可用於不同package的intent : (前面是package name, 後面是應用程式的component)
ComponentName componentName = new ComponentName("com.test", "com.test.TestActivity"); // 指定package


2. 指定intent的componentName
Intent intent = new Intent();
intent.setComponent(componentName);


3. 用intent切換到指定的Activity或是Service
(1) Avtivity
startActivity(intent);
(2) Service
startService(intent);

2011年2月28日 星期一

如何取得logcat

1. 執行相關指令
Runtime.getRuntime().exec("su");
Process p = Runtime.getRuntime().exec("logcat -d -v raw ActivityManager:I *:S");


2. 用串流接收列出來的訊息
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);


3. 讀取串流的資料,像是用readLine()
while((line=br.readLine())!=null)
{
    // code
}