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);

沒有留言:

張貼留言