티스토리 뷰

안드로이드 로컬 서비스를 이용한 액티비티와 서비스 통신.


액티비티에서 서비스 함수를 호출 하거나, 서비스에서 액티비티 함수를 호출하는 방법.

이 방법은 로컬서비스 바인딩 방법으로, 서비스를 앱내에서 품고 있는 경우에만 동작함.



액티비티 클래스 구현부...
public class MainActivity extends Activity {

//액티비티에서 선언.
private MainService mService; //서비스 클래스 

//서비스 커넥션 선언.
private ServiceConnection mConnection = new ServiceConnection() {
        // Called when the connection with the service is established
        public void onServiceConnected(ComponentName className, IBinder service) {
            MainService.MainServiceBinder binder = (MainService.MainServiceBinder) service;
            mService = binder.getService(); //서비스 받아옴
            mService.registerCallback(mCallback); //콜백 등록
        }

        // Called when the connection with the service disconnects unexpectedly
        public void onServiceDisconnected(ComponentName className) {
            mService = null;
        }
    };

//서비스에서 아래의 콜백 함수를 호출하며, 콜백 함수에서는 액티비티에서 처리할 내용 입력
private MainService.ICallback mCallback = new MainService.ICallback() {
        public void recvData() {

	//처리할 일들..

        }
    };

//서비스 시작.
public void startServiceMethod(View v){
        Intent Service = new Intent(this, MainService.class);
        bindService(Service, mConnection, Context.BIND_AUTO_CREATE);
    }

//액티비티에서 서비스 함수 호출

	mService.myServiceFunc();
}

서비스 클래스 구현부...

public class MainService extends Service {
//서비스에서 선언.

//서비스 바인더 내부 클래스 선언
 public class MainServiceBinder extends Binder {
        MainService getService() {
            return MainService.this; //현재 서비스를 반환.
        }
    }

private final IBinder mBinder = new MainServiceBinder();

 @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return mBinder;
    }

//콜백 인터페이스 선언
public interface ICallback {
        public void recvData(); //액티비티에서 선언한 콜백 함수.
    }

private ICallback mCallback;

//액티비티에서 콜백 함수를 등록하기 위함.
public void registerCallback(ICallback cb) {
        mCallback = cb;
    }

//액티비티에서 서비스 함수를 호출하기 위한 함수 생성
public void myServiceFunc(){
	//서비스에서 처리할 내용
    }


//서비스에서 액티비티 함수 호출은..
	
	mCallback.recvData(); 
}

위와같이 하면 서비스와 액티비티간 통신이 가능함.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함