我有一个上传活动,其中我调用Intent服务。在那里,我处理API请求调用。
我想让一个活动知道服务是否正在运行,以显示上传标签。
我尝试了以下方法来确定服务是否正在运行:
public void startUploadServiceTask() {
if (Util.isNetworkAvailable(mContext)) {
if (!isMyServiceRunning(UploadDriveService.class)) {
startService(new Intent(mContext,
UploadService.class));
}
} else {
Toast.makeText(mContext,
"Service is already running.", Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(mContext,
getString(R.string.please_check_internet_connection),
Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
Log.e("ALL SERVICE", service.service.getClassName().toString());
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
在“活动管理器运行服务信息”中,我无法获取正在运行的意图服务的类,因此这始终为false。
我已经使用广播来处理API调用的响应。
我甚至检查了这段代码。
if(startService(someIntent) != null) {
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
}
但是在这段代码中,检查服务时它也会重新启动服务,因此服务被调用了两次。
请帮我解决这个问题。