Android:如何确定IntentService是否正在运行?

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)

但是在这段代码中,在检查服务时它也会再次启动服务,因此服务被调用两次.

这个你能帮我吗.

AAD*_*ing 7

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是否正在运行!

  • 这不是线程安全的,因为onDestroy()是在与onHandleIntent()不同的线程中调用的.您应该使用synchronized()块来包围额外的代码. (3认同)

小智 1

在您的代码中,您尝试从“活动”获取服务的状态。正确的方法是状态应该由服务给出。

活动与服务通信有多种可能性,反之亦然。由于您使用广播接收器,因此您可以在服务启动时在 onHandleIntent() 方法中广播消息。

然后,当您的任务完成或出现任何错误时,您可以再次调用广播接收器来获取服务完成事件。

这是一个很好的教程的链接