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

标签 android android-intent service android-intentservice activity-manager

我有一个要从中调用 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/

相关文章:

android - 在 Lollipop 上启动 APN 设置 Activity

android - 有 20% 的时间从相机拍照失败

android - getResources() 在 Runnable 中显示错误

java - 如何在 WhatsApp 上将图像和文本一起分享给特定收件人?

c# - 无法从命令行或调试器启动服务

android - google 尝试登录 Android idToken :null

android - Snapshot Listener 如何处理离线数据?

android - 如何根据两个不同 Activity 中其他微调器的位置更改微调器的位置

java - 尽管很忙,但我的后台服务被杀死并等待了很长时间才重新启动

linux - 如何在宕机时使用 Systemd 重启服务?