: 같은
public class BindingActivity extends Activity {
YourService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
// Bind to Your Service
Intent intent = new Intent(this, YourService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Called when a button is clicked (the button in the layout file attaches to
* this method with the android:onClick attribute) */
public void onButtonClick(View v) {
if (mBound) {
// Call a method from your Service.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
int num = mService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
/** 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 the running Service, cast the IBinder and get instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
과 서비스를 제공합니다. RX를 사용하지 않는 경우 물론입니다. 개인적으로 가장 좋아하는 곳은 GreenRobot의 EventBus입니다. https://github.com/greenrobot/EventBus
몇 줄의 코드와 인터페이스가 없습니다. 이벤트를 시작하고 원하는 곳마다들을 수 있습니다. 그것은 분리되어 있으며 스레드로부터 안전하며 응용 프로그램을 손상시키지 않습니다.
숫자 3의 중대한보기 ... http://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from- a-background-service/ –
응용 프로그램을 닫으면 어떻게됩니까? 상태 활동으로 AlarmManager를 실행하는 경우 어떻게 처리 할 수 있습니까? – Basbous
기술 2와 3의 장단점은 무엇입니까? –