1. 程式人生 > >service怎麼執行到非UI執行緒

service怎麼執行到非UI執行緒

我們都知道android中service是執行在UI執行緒中的,怎樣讓service執行到非UI執行緒中?我知道service在註冊的時候可以通過android:process=":remote"指定service到remote的程序中,但是要讓service執行到非UI執行緒怎麼實現呢?

我們知道service作為一個後臺服務很可能會被系統給kill掉,那麼我們要想服務不被kill,有一個辦法就是把他變成前臺服務,startForeground(int id, Notification notification)。

在service中我們可以把耗時的操作放在一個執行緒中來處理,不知道這樣實現算不算service執行到非UI執行緒

還有一種就是service中自己的方法:onCreate(),onStart(), onStop(),onStartCommand(Intent intent, int flags, int startId)等都是屬於主執行緒中執行的,如果是呼叫service中的binder物件的方法,那就不是在UI執行緒中了,因為binder是在binder thread中處理。這樣來說,我麼可以通過bindService(Service service, ServiceConnection conn, int flags)方式讓activity和service建立關係,其中ServiceConnection的實現如下

ServiceConnection conn = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name)
{
// TODO 

}

@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
// TODO 
獲取binder物件來呼叫service裡面的操作,這裡做的操作就是在binder thread中完成的
}
};

自己的見解,不知道對否,大牛請指教。