Creating A Service In Android
I'm creating my first android app and I need to use a service. The UI will have a checkbox (CheckBoxPreference) that will be used to turn the service on/off and the service will on
Solution 1:
CheckBoxcheckBox=
(CheckBox) findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(newOnCheckedChangeListener() {
publicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startService(newIntent(this, TheService.class));
}
}
});
And the service:
publicclassTheServiceextendsService {
@Overridepublic IBinder onBind(Intent intent) {
returnnull;
}
@OverridepublicvoidonCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}
Solution 2:
In Android Studio, right-click package, then choose New | Service | Service. Now add this method:
@OverrideintonStartCommand(Intent intent, int flags, int startId) {
// Your code here...returnsuper.onStartCommand(intent, flags, startId);
}
Note: onStart is deprecated.
To start the service: From an activity's onCreate method (or a broadcast receiver's onReceive method):
Intent i = newIntent(context, MyService.class);
context.startService(i);
Post a Comment for "Creating A Service In Android"