[英]Android Service does not stop
I want to start/stop a service from an activity (like a switch button), but it does not stop. 我想从活动(如“切换”按钮)启动/停止服务,但它不会停止。
MainActivity.class MainActivity.class
btnGoToTrack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendIntentService.class);
boolean isServiceRunning = isServiceRunning(SendIntentService.class);
if (isServiceRunning == false) startService(intent);
else stopService(intent);
}
});
Check if service is online or not: 检查服务是否在线:
private boolean isServiceRunning(Class<?> pClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (pClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
The problem is isServiceRunning
is always returning me TRUE. 问题是
isServiceRunning
总是返回TRUE。 I don't know why. 我不知道为什么
SendIntentService.class: SendIntentService.class:
@SuppressLint("NewApi")
public class SendIntentService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("D: ", "SERVICE STARTED !");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("D: ", "SERVICE DISABLED !");
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
"The problem is isServiceRunning is always returning me TRUE. I don't know why." “问题是isServiceRunning总是返回TRUE。我不知道为什么。” shouldn't it be: "The problem is isServiceRunning is always returning me FALSE. I don't know why."?
不应该这样:“问题是isServiceRunning总是让我返回FALSE。我不知道为什么。”?
If it would always return TRUE it wouldn't start the service... 如果始终返回TRUE,则不会启动服务...
Did you check if pClass.getName() really equals service.service.getClassName()? 您是否检查过pClass.getName()是否真的等于service.service.getClassName()?
The problem was with my AVD. 问题出在我的AVD上。 I have several versions installed (while developing the app) and I think there was multiple services started.
我已经安装了多个版本(在开发应用程序时),并且我认为启动了多个服务。
I have removed all versions from my AVD (Settings -> Apps -> Uninstall app) and restarted the application. 我已经从AVD中删除了所有版本(设置->应用程序->卸载应用程序),然后重新启动了该应用程序。 Now it's working !
现在工作了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.