我有一个要从中调用 Intent 服务的上传 Activity 。我在那里处理 API 请求调用。
我想让一个 Activity 知道服务是否正在运行,以显示上传标签。
我尝试了以下操作以确定服务是否正在运行:
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;
}
但是在 Activity Manager Running Service Info 中,我没有得到我正在运行的 Intent 服务类,所以这总是错误的。
我已将广播用于 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();
}
但在此代码中,在检查服务时它还会再次启动服务,因此服务被调用了两次。
请帮我解决这个问题。
最佳答案
IntentService 需要实现 onHandleIntent()
此方法在工作线程上调用,请求处理 Intent 请求,只要 IntentService 正在处理 Intent 请求(am这里不考虑低内存等corener情况,只是从逻辑上考虑),
当所有请求都已处理后,IntentService 将自行停止,(因此您不应显式调用 stopSelf())
有了这个理论,您可以尝试以下逻辑:
在您的 IntentService 类中声明一个类变量。
public static boolean isIntentServiceRunning = false;
@Override
protected void onHandleIntent(Intent workIntent) {
if(!isIntentServiceRunning) {
isIntentServiceRunning = true;
}
//Your other code here for processing request
}
如果您愿意,可以在 IntentService 类的 onDestroy()
中设置 isIntentServiceRunning = false;
并使用 isIntentServiceRunning
检查 IntentService 是否正在运行!
关于Android:如何确定 IntentService 是否正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28298696/