Last active
March 20, 2018 06:18
-
-
Save li2/d8d3496f3f2e352ac71181e1f7d632f2 to your computer and use it in GitHub Desktop.
A basic abstract activity to bind & unbind service, its subclasses just override onServiceAttached(Service service) method to get the refercence of service. #tags: android-service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/a/38847374/2722270 | |
public abstract class BasicServiceActivity extends AppCompatActivity { | |
protected DvrService mDvrService; | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_basic); | |
attachService(); | |
} | |
@Override | |
protected void onDestroy() { | |
detachService(); | |
super.onDestroy(); | |
} | |
private ServiceConnection mServiceConnection = new ServiceConnection() { | |
@Override | |
public void onServiceConnected(ComponentName name, IBinder binder) { | |
DvrService.DvrServiceBinder serviceBinder = (DvrService.DvrServiceBinder) binder; | |
mDvrService = serviceBinder.getService(); | |
onServiceAttached(mDvrService); | |
} | |
@Override | |
public void onServiceDisconnected(ComponentName name) { | |
mDvrService = null; | |
} | |
}; | |
private void attachService() { | |
Intent service = new Intent(this, DvrService.class); | |
bindService(service, mServiceConnection, Service.BIND_AUTO_CREATE); | |
} | |
private void detachService() { | |
unbindService(mServiceConnection); | |
} | |
/** Callback when service attached. */ | |
protected void onServiceAttached(DvrService service) { | |
// do something necessary by its subclass. | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ServiceActivity extends BasicServiceActivity { | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
startService(new Intent(this, DvrService.class)); | |
} | |
@Override | |
protected void onDestroy() { | |
if (mDvrService != null) { | |
mDvrService.removeListener1(mListener1); | |
} | |
super.onDestroy(); | |
} | |
@Override | |
protected void onServiceAttached(DvrService service) { | |
// do your stuff, for example add a listener. | |
service.addListener1(mListener1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment