gpt4 book ai didi

java - Android 服务不停止

转载 作者:行者123 更新时间:2023-12-01 14:22:48 25 4
gpt4 key购买 nike

我想从 Activity (如开关按钮)启动/停止服务,但它不会停止。

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);
}
});

检查服务是否在线:

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;

问题是 isServiceRunning 总是返回 TRUE。我不知道为什么。

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;
}
}

最佳答案

“问题是 isServiceRunning 总是返回 TRUE。我不知道为什么。”不应该是:“问题是 isServiceRunning 总是返回 FALSE。我不知道为什么。”?

如果它始终返回 TRUE,则不会启动服务...

您检查过 pClass.getName() 是否真的等于 service.service.getClassName() 吗?

关于java - Android 服务不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17405175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com