Android 活动有时不起作用';无法使用ActivityManager找到服务
我正在为音频流开发一个非常简单的android应用程序。从活动开始,我启动和停止一个必须管理MediaPlayer的服务,每次打开主活动时,我都会检查该服务是否已在运行。 它工作正常,但我有一个问题,我无法解决 有一次,当服务仍在运行时打开应用程序,却找不到我的服务,我无法使用我实现的停止按钮停止它 下面是一些代码: 要检查服务是否正在运行,请执行以下操作:Android 活动有时不起作用';无法使用ActivityManager找到服务,android,service,android-activity,Android,Service,Android Activity,我正在为音频流开发一个非常简单的android应用程序。从活动开始,我启动和停止一个必须管理MediaPlayer的服务,每次打开主活动时,我都会检查该服务是否已在运行。 它工作正常,但我有一个问题,我无法解决 有一次,当服务仍在运行时打开应用程序,却找不到我的服务,我无法使用我实现的停止按钮停止它 下面是一些代码: 要检查服务是否正在运行,请执行以下操作: private boolean isMyServiceRunning() { ActivityManager manager =
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (StreamingRadio.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
然后在调用Activity onStart()时:
@Override
protected void onStart() {
super.onStart();
if(isMyServiceRunning()) {
streamingIsLive=true;
...
if(!isRegistered) {
registerReceiver(onNotice, new IntentFilter("startprogress"));
isRegistered=true;
}
}
}
和onStop()
至于我的播放和停止按钮:
public void onButtonPlay(View v) {
if(!streamingIsLive) {
streamingIsLive=true;
Intent intent = new Intent(this, StreamingRadio.class);
startService(intent);
....
}
}
public void onButtonStop(View v) {
if(streamingIsLive) {
streamingIsLive=false;
Intent intent = new Intent(this, StreamingRadio.class);
stopService(intent);
...
}
}
这个问题可能是什么?
谢谢您不应该使用
getRunningServices()
,因为它不用于生产,如中所述:
返回当前正在运行的服务的列表
注意:此方法仅用于调试或实现服务管理类型的用户界面。
相反,您必须不断引用服务是否在其
onCreate()
、onDestroy()
、onStartCommand()
、onLowMemory()
,等等中运行。如果我将最后一个静态myservice对象实例化到服务中并执行类似于:public onCreate()的操作,该怎么办{myserviceobject=this;…}和public onDestroy(){myserviceobject=null;…}我不知道可靠性/性能之间的最佳折衷是什么。
public void onButtonPlay(View v) {
if(!streamingIsLive) {
streamingIsLive=true;
Intent intent = new Intent(this, StreamingRadio.class);
startService(intent);
....
}
}
public void onButtonStop(View v) {
if(streamingIsLive) {
streamingIsLive=false;
Intent intent = new Intent(this, StreamingRadio.class);
stopService(intent);
...
}
}