Ruc*_*hah 6 service android android-intent activity-manager android-intentservice
我有一个上传活动,我称之为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;
}
Run Code Online (Sandbox Code Playgroud)
但是在Activity Manager Running Service Info中,我没有得到我正在运行的意向服务类,所以这总是假的.
我已经使用Broadcast for 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();
}
Run Code Online (Sandbox Code Playgroud)
但是在这段代码中,在检查服务时它也会再次启动服务,因此服务被调用两次.
这个你能帮我吗.
IntentService需要实现onHandleIntent()这个方法是在工作线程上调用的,请求处理Intent请求,只要它处理一个意图请求,IntentService就会"活着"(这里不考虑低内存和其他核心情况,但只是思考在逻辑方面),
并且当处理完所有请求后,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
}
Run Code Online (Sandbox Code Playgroud)
在onDestroy()IntentService类中,如果你可以选择,设置isIntentServiceRunning = false;
并用于isIntentServiceRunning检查IntentService是否正在运行!