ore*_*res 16 service android bind foreground aidl
这是第一个问题,但我已经有一段时间了.
我有什么:
我正在构建一个播放音频流和在线播放列表的Android应用.一切都工作正常,但我在与我的服务沟通时遇到问题.
音乐正在服务中播放,以startForeground开头,所以它不会被杀死.
我需要通过我的活动与服务进行沟通,以获取曲目名称,图像和更多内容.
我的问题是什么:
我想我需要使用bindService(而不是我当前的startService)启动我的服务,以便活动可以与它通信.
但是,当我这样做时,我的服务在关闭Activity后被杀死.
我怎样才能得到这两个?绑定和前台服务?
谢谢!
Lib*_*bin 17
号bindService
不会启动服务.它只会绑定到Service
a service connection
,因此您将拥有instance
访问/控制它的服务.
根据您的要求,我希望您将拥有MediaPlayer
服务实例.您也可以从该服务Activity
,然后bind
它.如果service
已经在运行,onStartCommand()
则可以检查MediaPlayer
实例是否为null,然后返回START_STICKY
.
改变你Activity
这样..
public class MainActivity extends ActionBarActivity {
CustomService customService = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start the service, even if already running no problem.
startService(new Intent(this, CustomService.class));
// bind to the service.
bindService(new Intent(this,
CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
customService = ((CustomService.LocalBinder) iBinder).getInstance();
// now you have the instance of service.
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
customService = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (customService != null) {
// Detach the service connection.
unbindService(mConnection);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有类似的应用程序MediaPlayer
service
.如果这种方法对您没有帮助,请告诉我.
小智 11
引用Android文档:
除非服务也已启动,否则绑定服务将在所有客户端解除绑定后销毁
关于启动和绑定之间的区别,请查看https://developer.android.com/guide/components/services.html
因此,您必须使用startService
,然后bindService
像@Libin在他/她的示例中那样创建服务.然后,该服务将运行,直到您使用stopService
或stopSelf
或直到安卓决定其需要的资源和杀死你.
归档时间: |
|
查看次数: |
9319 次 |
最近记录: |