'Is it intended behavior for a bound-only service to become a foreground service?
This question is a result of my previous question.
Can a bound service call startForeground? The example code is below, but in brief, I was able to sucessfully call startForeground (i.e. the foreground notification appeared) inside of the onBind method even when the service was never started (i.e. no calls were made to startService). Is this intended behavior? I was under the (false?) notion that foreground services were only for started services.
This was tested on API level 32.
public class MyService extends Service {
// other implementation...
// define myStartForeground which internally calls startForeground(...)
private class LocalBinder extends Binder {
public MyService getService() { return MyService.this; }
}
private final LocalBinder localBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
myStartForeground()
return local_binder;
}
}
public class MainActivity extends Activity {
private final ServiceConnection serviceConnection = // create ServiceConnection instance
private boolean bound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final button = findViewById(R.id.button);
button.setOnClickListener(this::onButtonClick);
}
private void onButtonClick(View view) {
if(!bound) {
bindService(new Intent(this, MyService.class), serviceConnection, BIND_AUTO_CREATE);
} else {
unbindService(serviceConnection);
}
bound = !bound;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
