小编Ruc*_*hah的帖子

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(), …
Run Code Online (Sandbox Code Playgroud)

service android android-intent activity-manager android-intentservice

6
推荐指数
2
解决办法
9839
查看次数