0
(here)이며 모든 개발자가 그러하므로 Activity
이 Service
과 통신하는 데는 여러 가지 방법이 있습니다. 가장 인기있는 방법은 인 텐트 데이터와 바인딩을 사용하는 것입니다. 단순히 그것의 메소드를 호출함으로써 서비스와 통신 할 수 있습니까? 가능하다면 좋은 방법일까요?그것의 메소드를 호출하여 서비스와 통신 할 수 있습니까?
(here)이며 모든 개발자가 그러하므로 Activity
이 Service
과 통신하는 데는 여러 가지 방법이 있습니다. 가장 인기있는 방법은 인 텐트 데이터와 바인딩을 사용하는 것입니다. 단순히 그것의 메소드를 호출함으로써 서비스와 통신 할 수 있습니까? 가능하다면 좋은 방법일까요?그것의 메소드를 호출하여 서비스와 통신 할 수 있습니까?
예, 바인더에서 서비스 인스턴스를 반환하면됩니다. 이렇게하는 방법에 대한 예제는 at this article을보십시오.
위의 기사에서 추출한 내용 (줄을 찾으십시오 : int num = mService.getRandomNumber();
).
LocalService.java
public class LocalService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public int getRandomNumber() {
return 5;
}
}
BindingActivity.java
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
// Call the method from service
int num = mService.getRandomNumber();
}
};
}
는 좋은 합리적인 방법이 있나요? – Soheil
@Soheil - 예, 완전히 합리적입니다. 이 서비스에서 호출하는 모든 메소드는 활동과 동일한 스레드에서 호출된다는 점을 기억하면됩니다. 따라서 장기 실행 작업을하기 위해이 서비스가 필요하다면'AsyncTask', 쓰레드 또는 유사한 것을 사용하십시오. – kamituel