2013-09-05 2 views

답변

1

예, 바인더에서 서비스 인스턴스를 반환하면됩니다. 이렇게하는 방법에 대한 예제는 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(); 
     } 
    }; 
} 
+0

는 좋은 합리적인 방법이 있나요? – Soheil

+1

@Soheil - 예, 완전히 합리적입니다. 이 서비스에서 호출하는 모든 메소드는 활동과 동일한 스레드에서 호출된다는 점을 기억하면됩니다. 따라서 장기 실행 작업을하기 위해이 서비스가 필요하다면'AsyncTask', 쓰레드 또는 유사한 것을 사용하십시오. – kamituel

관련 문제